gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:30:26 25 4
gpt4 key购买 nike

所以我一直在尝试从我拥有的数组中位移 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com