我想与一个结构和一个uint64_t进行联合,所以我可以引用单个uint16_ts与结构,并将它们串联在uint64_t中。我在此测试程序:结构和整数的内存顺序
#include "stdio.h"
#include "stdint.h"
struct test_struct{
uint16_t stuff;
uint16_t a;
uint16_t b;
uint16_t c;
};
union test_union{
struct test_struct str;
uint64_t uint;
};
int main(){
struct test_struct x = {
.stuff = 0x0000,
.a = 0x1234,
.b = 0x5678,
.c = 0x9ABC
};
union test_union y;
y.str = x;
printf("y.uint: %llX\n", y.uint);
}
输出成为:
y.uint: 9ABC567812340000
其是反直觉的,我(它是768,16 000ABC,或123456789ABC)。有人可以向我解释为什么结构中的元素似乎被颠倒了吗?
编辑: 供将来参考:字节顺序的答案让我感到困惑,因为uint16_ts是按照正确的顺序打印的。但是,这当然是因为它们本身存储的是小端。