我正在编写 C 代码,以便使用 Windows(codeblocks IDE)x64 intel PC 中的 GCC C 编译器从写入网络字节顺序的二进制文件中读取数据。
数据字节如下:
00 16 54 43 41 54 20 20 00 AA 00 00 00 00 00 00 B8 60 41 42 43 00 00 17
我的代码是:
#define SWAPPED(num) ((num>>8) | (num<<8))
struct trd_t {
unsigned short length; // First 2 bytes in the input data
char type; // next 1 byte
char symbol[5]; // next 5 bytes
unsigned short trd_size; // next 2 bytes
uint64_t trd_price; // next 8 bytes
}; __attribute((packed))__; // <--- EDIT: I tried this packed, but does not give right values either.
main ()
{
struct trd_t *trd;
unsigned char *buffer;
unsigned short len;
unsigned char type;
...
buffer = (unsigned char*) malloc(pkt_len);
fread(buffer, pkt_len, 1 , fp)
trd = (struct trd_t *) buffer;
len = SWAPPED(trd->length);
if (trd->type == 'T') {
....
}
...
转换 (struct trd_t *)buffer 后,所有前几个结构元素都捕获了正确的数据,例如长度、类型、符号和 trd_size。
然而,trd_price 是错误的。
我期望它捕获“00 00 00 00 00 00 B8 60”
但是,它捕获“B8 60 41 42 43 00 00 17”
我尝试使用“attribute((packed));”在结构上,但它也没有帮助。
有什么想法吗?
最佳答案
如果您发现一个与您可能碰巧在某处找到的某些二进制数据完全匹配的 struct
布局,这或多或少纯粹是运气(并且可能会在编译器的下一个版本中崩溃)。
C 不对结构成员对齐或填充做出任何保证,尽管packed
可能有所帮助。
您应该将文件内容分段读取到适当大小的字节缓冲区中,并从那里提取您的 struct
成员。
关于c - 在网络字节顺序上使用结构时得到错误的字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766990/