我有一个 12 字节的数据包要发送,格式如下:
+--------+------+ | ID | ver | +--------+------+
ID is 8 bytes and ver is 4 bytes. I have declared a struct as below but my PC gives me a size value of 16 bytes (8 + 4 + 4 byte of padding). #pragma
solved the problem, but is there any way to solve the issue?
struct pak
{
char *ID;
uint32_t ver;
};
最佳答案
最通用、可移植和防错的解决方案是根本不关心填充。
您可以使用memcpy
将结构序列化和反序列化为字符数组,而不是按原样发送结构。
在向其他设备发送数据时,您不应该忘记字节顺序 - 请参阅ntohl
和ntohs
的文档以了解详细信息。
关于c - 如何发送带有填充字段的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14068928/