gpt4 book ai didi

c++ - 在 C/C++ 中从 int32 转换为 char 时出现垃圾

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:24:44 27 4
gpt4 key购买 nike

我正在使用一个简单的代码将 uint32_t 变量转换为 char。

uint32_t len = 4 + data.length(); //data is a string
char pop1 = len & 0xff;
char pop2 = (len >> 8) & 0xff;
char pop3 = (len >> 16) & 0xff;
char pop4 = (len >> 24) & 0xff; //also tried the same thing with memcpy

printf("%02x \n",pop1);
printf("%02x \n",pop2);
printf("%02x \n",pop3);
printf("%02x \n",pop4);

输出:

ffffff81
02
00
00

我不明白为什么垃圾添加到第一个字节。当我改用 unsigned char 时,没有添加垃圾。在我的理解中,char 和 unsigned char 都是 8 位的,那么为什么将 char 视为 32 位值。我在 64 位 Windows 机器上使用 VS2015。我想使用 char 数组作为 WinSock2 的发送函数。

send(ConnectSocket, sendbuf, size_to_send, 0); // sendbuf is a char array

最佳答案

当小整数类型的值(如 char )作为参数传递给可变参数函数(如 printf )时,它是 promotedint

如果小类型是 signed,此促销可以包括符号扩展 .

关于 two's complement表示 int 的系统(这是绝大多数计算机很长一段时间)将填充 1位,打印为 unsigned int十六进制将显示为 f .

简单的解决方案是不使用 char , 但最好是 uint8_t或明确的 unsigned char为您的变量键入。

关于c++ - 在 C/C++ 中从 int32 转换为 char 时出现垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543292/

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