Converting unsigned chars to signed integer

前端 未结 4 2217
轻奢々
轻奢々 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:38

    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

    0 讨论(0)
  • 2021-02-09 20:42

    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].)

    0 讨论(0)
  • 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 ;)

    0 讨论(0)
  • 2021-02-09 20:53

    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]
    
    0 讨论(0)
提交回复
热议问题