如何判断机器的endianness
字节层次上
_Bool is_little_endian() { int a = 1; char* p = (char*)&a; return *p == 1; }
或
_Bool is_little_endian() { union { int a; char b; } u; u.a = 1; return u.b == 1; }
位层次上
_Bool is_little_endian() { union { unsigned char a; struct { unsigned char b0 : 1; unsigned char : 7; } b; } u; u.a = 1; return u.b.b0 == 1; }
比较同一块内存的不同表示
big endian:
+----+----+----+----+
| 00 | 00 | 00 | 01 |
+----+----+----+----+
-------- 内存地址增长 -------->
little endian:
+----+----+----+----+
| 01 | 00 | 00 | 00 |
+----+----+----+----+
-------- 内存地址增长 -------->