字节顺序

本文详细解释了字节顺序的概念,包括Big-Endian和Little-Endian的区别,通过实例展示了如何判断当前系统使用的字节顺序,并讨论了CPU体系结构对字节顺序的影响。

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

endian

就是字节顺序的意思


big-endian

现在在纸上书写阿拉伯数字198,我们肯定是先写最高位1,直到写到最低位8,如果让计算机采用这个顺序存放数据到内存中,也就是现在起始地址放最高位1,然后写上9,最好是8.这样的顺序就是big endian.


little-endian

与其顺序相反的是,低位地址存放低位数字,高位地址存放高位数字。这种最合乎计算机内存地址的写法就是little endian.


如果没有明白我说的,看下面的表。

EndianFirst byte
(lowest address)
Middle bytesLast byte
(highest address)
Notes
big mostsignificant... leastsignificantSimilar to a number written on paper (inArabic numeralsas used in most Western scripts)
little leastsignificant... mostsignificantArithmetic calculation order (seecarry propagation)

下面的函数帮助判断是big-endian还是little-endian. 很简单,取最低位字节的整数,比较是不是最低位数字ff,是就是little-endian.

bool little_endian(){
  int x = 0x00ff;
  char* p = (char*)&x;
  return (int)p[0]==-1;
}

字节顺序是由CPU体系结构或者其他硬件决定的。下面的描述同样来自于wikipedia

Well-known processors that use the big-endian format includeMotorola 6800and68k, XilinxMicroblaze,IBM POWER, andSystem/360and its successors such asSystem/370,ESA/390, andz/Architecture. ThePDP-10also used big-endian addressing for byte-oriented instructions.SPARChistorically used big-endian until version 9, which is bi-endian, similarly theARM architecturewas little-endian before version 3 when it became bi-endian, and thePowerPCandPower Architecturedescendants of IBM POWER are also bi-endian (see below).

Serial protocols may also be regarded as either little or big-endian at the bit- and/or byte-levels (which may differ). Many serial interfaces, such as the ubiquitousUSB, are little-endian at the bit-level. Physical standards likeRS-232,RS-422andRS-485are also typically used withUARTsthat send the least significant bit first, such as in industrial instrumentation applications, lighting protocols (DMX512), and so on. The same could be said for digitalcurrent loopsignaling systems such asMIDI. There are also several serial formats where the most significant bit is normally sent first, such asI²Cand the relatedSMBus. However, the bit order may often be reversed (or is "transparent") in the interface between theUARTorcommunication controllerand the hostCPUorDMAcontroller (and/or system memory), especially in more complex systems and personal computers. These interfaces may be of any type and are often configurable.


CPU的endian有些是允许设置的。因此唯一不变的是不确定性,运行时用上面的函数检查endian才是比较靠谱的做法,不能简单用CPU体系来判断。

浮点数是个比较复杂的问题,并不一定和同一系统的整数字节顺序一致,有的刚好相反。有的还存在half little-endian和half big-endian的组合。将在别的文章中描述。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值