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

本文介绍了计算机中两种主要的字节序组织方式:大端序(bigendian)和小端序(littleendian)。通过引用《格列佛游记》中的典故来解释这两种字节序的名称由来,并提供了具体的定义说明以及一段测试代码来检测机器所采用的字节序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现代机器的字节序组织有两种方式,即大端序组织(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;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值