小端vs大端 [英] Little endian Vs Big endian

查看:96
本文介绍了小端vs大端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有4个字节的整数,我想将其转换为2个字节的短整数.我是对的(小端和大端)短整数是否都将由该4Byte整数中的2个最低有效字节组成?

Lets say I have 4Byte integer and I want to cast it to 2Byte short integer. Am I right that in both (little and big endian) short integer will consist of 2 least significant bytes of this 4Byte integer?

第二个问题:
在小字节序和大字节序处理器中,这样的代码会产生什么结果?

Second question:
What will be the result of such code in little endian and big endian processor?

int i = some_number;  
short s = *(short*)&i;

在大字节序处理器中,IMHO将复制2个最高有效字节,在小字节序处理器中,将复制2个最低有效字节.

IMHO in big endian processor 2 most significant bytes would be copied, and in little endian 2 least significant bytes would be copied.

推荐答案

我对吗,两个短整数都将由这个4字节整数中的2个最低有效字节组成?

Am I right that in both short integer will consist of 2 least significant bytes of this 4Byte integer?

是的,根据定义.

bigE和littleE之间的区别在于,最低有效字节是否位于最低地址.在小字节序处理器上,最低地址是最低有效位,x86就是这样做的.

The difference between bigE and littleE is whether the least significant byte is at the lowest address or not. On a little endian processor, the lowest addresses are the least significant bits, x86 does it this way.

这些在小E上给出相同的结果.

These give the same result on little E.

short s = (short)i;
short s = *(short*)&i;

在大型字节序处理器上,最高地址是最低有效位,68000和Power PC就是这样做的(实际上Power PC可以是两者,但是Apple的PPC计算机使用bigE)

On a big endian processor, the highest addresses are the least significant bits, 68000 and Power PC do it this way (actually Power PC can be both, but PPC machines from Apple use bigE)

在大E上给出相同的结果.

These give the same result on big E.

short s = (short)i;
short s = ((short*)&i)[1]; // (assuming i is 4 byte int)

因此,如您所见,little endian允许您获得操作数的最低有效位,而无需知道操作数的大小. little E具有保持向后兼容性的优点.

So, as you can see, little endian allows you to get at the least significant bits of an operand without knowning how big it is. little E has advantages for preserving backward compatibility.

那么big endian有什么优势? 它创建易于阅读的十六进制转储.

So what's the advantage of big endian? It creates hex dumps that are easier to read.

确实,摩托罗拉的工程师认为减轻读取十六进制转储的负担比向后兼容更为重要.英特尔的工程师则相反.

Really, the engineers at Motorola thought that easing the burden of reading hex dumps was more important than backward compatibility. The engineers at Intel believed the opposite.

这篇关于小端vs大端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆