Friday, 15 May 2015

c - Efficiently convert unsigned to signed -



c - Efficiently convert unsigned to signed -

i subtract 32768 when have unsigned short want convert signed one.

is fastest way it, or there faster ways?

if value between 0 shrt_max (inclusive), there's nil worry , cast ((short)) optional (unless compiler paranoid or configured paranoid).

if unsigned short value can greater shrt_max, legal way convert short is:

#include <limits.h> short ushort2short(unsigned short s) { if (s <= shrt_max) homecoming s; // or homecoming (short)s; s -= shrt_max + 1; // s 0 ... shrt_max homecoming (short)s - shrt_max - 1; }

this, of course, relies on signed shorts beingness 2's complement shrt_min = -shrt_max - 1.

a modern compiler optimize away nonsense within function , generate code homecoming s.

edit: compiled above gcc 4.6.2 gcc -wall ush2sh.c -o2 -s -o ush2sh.s assembly code:

.file "ush2sh.c" .text .p2align 2,,3 .globl _ushort2short .def _ushort2short; .scl 2; .type 32; .endef _ushort2short: lfb0: .cfi_startproc movl 4(%esp), %eax ret .cfi_endproc lfe0:

c optimization casting c99

No comments:

Post a Comment