union
{
unsigned long bits32;
unsigned char bytes[4];
} unValue;
unValue.bytes[0] = 0;
unValue.bytes[1] = 1;
unValue.bytes[2] = 0;
unValue.bytes[3] = 0;
isLittleEndian = ( unValue.bits32 == 256 );
//
union虽然也可以像struct那样声明多个域
但是与struct不同的是
struct各域的内存空间是独立的
而union各域的内存首地址是相同的
也就是union里的各域共享彼此的内存
因此你改了其中一个域的话也会同时更改其他域的值
具体到这个例子我申明了个union
它有两个域unsigned long bits32和unsigned char bytes[4]
它们都是32位且共用同一段内存
如下图
| bytes[0] | bytes[1] | bytes[2] | bytes[3] |
00000000 00000000 00000000 00000000
|<---------------bits32-------------------->|
当unValue.bytes[0] = 0;
unValue.bytes[1] = 1;
unValue.bytes[2] = 0;
unValue.bytes[3] = 0;
赋值过后这段内存变为
| bytes[0] | bytes[1] | bytes[2] | bytes[3] |
00000000 00000001 00000000 00000000
|<---------------bits32-------------------->|
在小端机器上这段内存作为unsigned int的话值为256,而在大端机器上作为unsigned int的话其值是65536
因此用bits32与256进行比较
如果为真说明是小端机器
如果为假说明是大端机器