分类: C/C++
2006-09-07 21:25:33
关于endian这个词Pconline上的解释如下:
“endian”这个词出自《格列佛游记》。小人国的内战就源于吃鸡蛋时是究竟从大头(Big-Endian)敲开还是从小头(Little-Endian)敲开,由此曾发生过六次叛乱,其中一个皇帝送了命,另一个丢了王位。
我们一般将endian翻译成“字节序”,将big endian和little endian称作“大尾”和“小尾”。 82 struct iphdr { 83 #if defined(__LITTLE_ENDIAN_BITFIELD) 84 __u8 ihl:4, 85 version:4; 86 #elif defined (__BIG_ENDIAN_BITFIELD) 87 __u8 version:4, 88 ihl:4; 89 #else 90 #error "Please fix 91 #endif 92 __u8 tos; 93 __be16 tot_len; 94 __be16 id; 95 __be16 frag_off; 96 __u8 ttl; 97 __u8 protocol; 98 __u16 check; 99 __be32 saddr; 100 __be32 daddr; 101 /*The options start here. */ 102 }; |
u_int16_t x = 0x1; u_int8_t xx[2]; memcpy(xx, x); |
x[0] x[1] --------- 15 ... 0 --------- 00 01 |
x[1] x[0] --------- 15 ... 0 --------- 00 01 |
union { u_int16_t num; struct { u_int8_t a4 : 4; u_int8_t b8; u_int8_t c4 : 4; } b; } a; a.b.a4 = 0x01; a.b.b8 = 0x0203; a.b.c4 = 0x04; a.num = ? |
--------------------- | 7-4|3-0 | 7-4|3-0 | --------------------- | a[0] | a[1] | --------------------- | a4 | b8 | c4 | --------------------- | 01 | 02 | 03 | 04 | --------------------- | 0x01020304 | --------------------- |
--------------------- | 7-4|3-0 | 7-4|3-0 | --------------------- | a[1] | a[0] | --------------------- | c4 | b8 | a4 | --------------------- | 04 | 02 | 03 | 01 | --------------------- | 0x04020301 | --------------------- |