测试机器大小端字节序的小程序

来源:互联网 发布:华电电科院 知乎 编辑:程序博客网 时间:2024/04/27 14:22

现代机器的字节序组织有两种方式,即大端序组织(big endian)和小端序组织(little endian),典型的Intel 80x86 CPU使用的是little endian,而苹果Macintosh和大多数非80x86的系统使用的是big endian。

 这两个名字来源于Jonathan Swift 的作品《格列佛游记》(Gulliver's Travels),小人国的居民们争吵不决鸡蛋是应该从大的一端打开还是应该从小的一端打开,后来计算机的字节序组织也沿用了这种叫法。。。

关于little endian的解释:"Little Endian" means that the low-order byte of the number is stored in memory at the lowest address, and the high-order byte at the highest address.

关于big endian的解释:"Big Endian" means that the high-order byte of the number is stored in memory at the lowest address, and the low-order byte at the highest address.

下面是一段测试机器大小端字节序的代码

#include<stdio.h>

union
{
        unsigned 
long bits32;
        unsigned 
char bytes[4];
}
value;

int isLittleEndian(){
        value.bytes[
0= 0;
        value.bytes[
1= 1;
        value.bytes[
2= 0;
        value.bytes[
3= 0;

        
return value.bits32 == 256;
}


int main(){
        
if( isLittleEndian())
                printf(
"is little endian! ");
        
else
                printf(
"is big endian! ");
        
return 0;
}
 
原创粉丝点击