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

标签 c bit-shift

所以我一直在尝试从我拥有的数组中位移 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促销完成前的值(value)。所以 number = buffer[0] << 8 | buffer[1];应该是

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

关于c - 从数组中对 c 中的 2 个字节进行位移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928457/

相关文章:

c - 引用二维数组的一维

java - 删除特定索引处的位

c++ - 15 位颜色分量,位移位

c - 存储在 1 字节数组中的浮点型位移

c - 哪种有符号整数除法对应位移位?

ios - Objective-C,计算一组值的所有可能总和以达到结果目标

c - 如何释放在双指针结构上分配的内存

c - argv[argc] 是否等于 NULL 指针

objective-c - 什么是_Complex?

c++ - C++ 移位运算符的思考