gpt4 book ai didi

c++ - 在 C/C++ 中重构数字

转载 作者:搜寻专家 更新时间:2023-10-31 00:47:49 24 4
gpt4 key购买 nike

我有一个从套接字(小端)读取的字节流。有人能告诉我为什么只有下面的最后一种方法给出正确答案吗?我怀疑这与进位有关,但不确定。我总是发现当以十六进制形式打印二进制数据。

例如

printf("%02X", data);

它有时会打印出前面带有 0xff 的有趣值。修复它的方法似乎做这个。当数据也是 char 数据类型时,这仍然偶尔会发生:

printf("%02X", data & 0xff);

这是我在字节流中看到的一个简化示例。其中 bytes 是我从套接字中读取的字节流。

int main(int argc, char* argv[])
{
union {
unsigned int num;
char bytes[4];
} x;

x.num = 500;
printf("x.num=%u\n", x.num);

unsigned int method1 = x.bytes[0] | (x.bytes[1] << 8) | (x.bytes[2] << 16) | (x.bytes[3] << 24);
printf("method1 = %u\n", method1);

unsigned int method2 = x.bytes[0] + (x.bytes[1] << 8) + (x.bytes[2] << 16) + (x.bytes[3] << 24);
printf("method2 = %u\n", method2);

unsigned int method3 = (x.bytes[0] & 0xff | (x.bytes[1] & 0xff) << 8
| (x.bytes[2] & 0xff) << 16 | (x.bytes[3] & 0xff) << 24);
printf("method3 = %u\n", method3);

return 0;
}

哪些输出:

x.num=500
method1 = 4294967284
method2 = 244
method3 = 500

只有最后一段摘录是正确的。我建立数字的方法是最佳的吗?我还尝试了一个变量的 memcpy 但同样不可靠。

最佳答案

当有符号数据类型被转换为更高的数据类型时,最高有效位用作符号位。你的 union 中应该有 unsigned char。在您的情况下,500 = 256 + 244 = 0x1f4 并且字节 244 设置了最高有效位,因此提升后变为 0xfffffff4。

关于c++ - 在 C/C++ 中重构数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436749/

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