Converting unsigned chars to signed integer

前端 未结 4 2216
轻奢々
轻奢々 2021-02-09 20:11

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: The unsigne

4条回答
  •  有刺的猬
    2021-02-09 20:48

    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 ;)

提交回复
热议问题