开发者

Converting unsigned chars to signed integer

开发者 https://www.devze.com 2023-02-06 22:47 出处:网络
I have an unsigned char array with 2 elements that represents a signed integer. How can I convert these 2 bytes into a signed integer?

I have an unsigned char array with 2 elements that represents a signed integer. How can I convert these 2 bytes into a signed integer?

Edit: Th开发者_StackOverflow社区e unsigned char array is in little endian


For maximum safety, use

int i = *(signed char *)(&c[0]);
i *= 1 << CHAR_BIT;
i |= c[1];

for big endian. Swap c[0] and c[1] for little endian.

(Explanation: we interpret the byte at c[0] as a signed char, then arithmetically left shift it in a portable way, then add in c[1].)


wrap them up in a union:

union {
  unsigned char a[2];
  int16_t smt;
} number;

Now after filling the array you can use this as number.smt


It depend of endianness. Something for big endian :

unsigned char x[2];
short y = (x[0] << 8) | x[1]

Something for little endian :

unsigned char x[2];
short y = (x[1] << 8) | x[0]


The portable solution:

unsigned char c[2];
long tmp;
int result;

tmp = (long)c[0] << 8 | c[1];
if (tmp < 32768)
    result = tmp;
else
    result = tmp - 65536;

This assumes that the bytes in the array represent a 16 bit, two's complement, big endian signed integer. If they are a little endian integer, just swap c[1] and c[0].

(In the highly unlikely case that it is ones' complement, use 65535 instead of 65536 as the value to subtract. Sign-magnitude is left as an exercise for the reader ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消