Converting unsigned chars to signed integer

前端 未结 4 2223
轻奢々
轻奢々 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: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].)

提交回复
热议问题