从数组中对 c 中的 2 个字节进行位移

bitshifting 2 bytes in c from an array

所以我一直在尝试从我拥有的数组中位移 2 个字节,有时我会得到很好的值,但并非总是如此。所以这是一个例子。

    char buffer[2]; //current character buffer to store the bytes
    unsigned int number; //the unsigned int to store values

    number = buffer[0] << 8 | buffer[1]; //bitshifting
    printf("%02x ", number);

我似乎在某些情况下得到了这个。

    ffffffbc // the bc seems to be correct however the f's are not 

这是因为char被提升为整数,带有符号位,在提升完成之前需要转换为unsigned值。所以 number = buffer[0] << 8 | buffer[1]; 应该是

number = (unsigned char)buffer[0] << 8U | (unsigned char)buffer[1];