繁体   English   中英

将 char[] 转换为 C++ 中的结构时,计算机会忽略一个字节

[英]A byte is ignored by the computer when casting a char[] to a struct in C++

我正在编写一个客户端-服务器程序,其中客户端使用 C++ 编写,服务器端使用 Python。

一个字节的 stream 从服务器端发送并接收到char[]缓冲区,然后使用reinterpret_cast转换为适当的结构。

char response_buffer[7];
recv(sock, response_buffer, 7, 0);
s_response* response = reinterpret_cast<s_response*>(response_buffer);
cout << response -> code << endl;

结构是这样定义的:

typedef struct {
    unsigned char version;
    unsigned short code;
    unsigned int payload_size;
} s_response;

但不是version1 字节)获得response_buffer[0]中的值, code获得response_buffer[1]response_buffer[2]两个字节), code最终获得response_buffer[2]response_buffer[3]中的值,而payload_sizeresponse_buffer[4]变为response_buffer[6] ,因此,值response_buffer[1]没有插入到任何结构的属性中,结果是一团糟。

起初,我认为这是由于字节顺序,但是当我从服务器端发送值2200113821时,以下值在response_buffer中:

0. 00000010
1. 11101001
2. 00000011
3. 11111101
4. 00110101
5. 00000000
6. 00000000

我期望得到的,并且顺序正确。 但是当我打印出response->code时,我得到的值是64771 ,即11111101 00000011 (上面列表中的 2 和 3),而不是2001 ,即00000011 11101001 (列表中的 1 和 2)。 意思是,当我将char*转换为s_response*时, response_buffer中 position 1 中的字节将被忽略,并且从那里开始的值从正确的顺序偏移了一个字节。

知道我在做什么错吗?

正如评论中所写,是结构填充造成了问题。 可以通过添加#pragma来解决,如下图

#pragma pack(push,1)
typedef struct {
    unsigned char version;
    unsigned short code;
    unsigned int payload_size;
} s_response;
#pragma pack(pop)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM