由于不完全理解您的问题,我删除了我的原始答案。在阅读以下文章后,我现在明白了:Writing endian-independent code in C
首先是对齐问题:
如 500 所述 - 内部服务器错误
您在处理数据时会遇到问题,因为您的结构将包含填充。在您的示例中,将向结构添加 1 个字节。
这是一个从 VS 获得的 32 位 C 实现的内存布局示例。
size = 8
Address of test0 = 5504200
Padding added here at address 5504201
Address of test1 = 5504202
Address of test2 = 5504204
要指定编译器应该使用的对齐规则,请使用预处理器指令pack。
// Aligns on byte boundaries, then restore alignment value to system defaults
#pragma pack ( 1 )
#pragma pack ()
// Aligns on byte boundaries, restores previously assigned alignment value.
#pragma pack ( push, 1 )
#pragma pack (pop)
使用您的示例,结构定义将如下所示:
#pragma pack ( 1 )
typedef struct {
unsigned char test0;
unsigned short test1;
unsigned int test2;
} Foo_t;
#pragma pack ()
Foo_t s2;
printf("\nsize = %d\n", sizeof(Foo_t));
printf(" Address of test0 = %u\n", &s2.test0);
printf(" Address of test1 = %u\n", &s2.test1);
printf(" Address of test2 = %u\n", &s2.test2);
结果:
size = 7
Address of test0 = 10287904
Address of test1 = 10287905
Address of test2 = 10287907
第二个字节序问题:
这里的问题是整数是如何存储在 32 位 x86 机器上的内存中的。在 x86 机器上,它们以 little endian 顺序存储。
例如,将包含字节 x34 和 x56 的 2 字节数组复制到一个短整数中,将存储为 x56(低位字节)x34(下一个字节)。这不是你想要的。
要解决此问题,您需要按照其他建议切换字节。我对此的看法是创建一个可以就地进行字节交换的函数。
例子:
int main()
{
#pragma pack ( 1 )
typedef struct {
unsigned char test0;
unsigned short test1;
unsigned int test2;
} Foo_t;
#pragma pack ()
unsigned char tempBuf[7] = { 0x12, 0x34, 0x56, 0x78, 0x0A, 0x06, 0x77 };
Foo_t foo;
memcpy(&foo, &tempBuf[0], 7);
//foo.test0 = netToHost (&foo,0,1); // not needed
foo.test1 = reverseByteOrder(&foo, 1, 2);
foo.test2 = reverseByteOrder(&foo, 3, 4);
printf("\n After memcpy We have %02X %04X %08X\n", foo.test0, foo.test1, foo.test2);
}
int reverseByteOrder(char array[], int startIndex, int size)
{
int intNumber =0;
for (int i = 0; i < size; i++)
intNumber = (intNumber << 8) | array[startIndex + i];
return intNumber;
}
输出是:
After memcpy We have 12 3456 780A0677