读取 32 位架构中的 Shorts(例如) [英] Reading shorts in 32-bits architectures (for example)
问题描述
首先,对不起我的英语.
First of all, sorry for my English.
我知道架构非常复杂,情况也很广泛,但一个普遍的概括是,如果计算机架构有 32 位字,则意味着寄存器、内存访问和总线使用 32 位长的字(但我认为当前架构中有很多变体).
I know architectures are very complex and there's a broad sprectrum of situations, but a common generalization is if a computer architecture has 32-bits words, means registers, memory accesses and buses work with words of 32-bits long (but I think there's a lot of variants in current architectures).
好的,让我们假设这是规则,我们的架构是小端的,如 x86.在这种情况下,如果我们想读取一个 short int
(2 字节长),内存会读取包含我们的 short
的 4 字节字.假设包含单词 W 是 0xf1342ea0
,在内存中:
Ok, let's suppose this is the rule and our architecture is a little-endian one, as x86. In such a case, if we want to read a short int
(2-bytes long), the memory reads then the 4-bytes word which contains our short
. Let's suppose the containing word W is 0xf1342ea0
, in memory:
{a0, 2e, 34, f1} // a0 is the byte in the lowest address.
我们的半字H在W的最高部分,那么,H就是0xf134.我知道处理器从内存中接收到一个带有 short
移位的单词:
and our half-word H is in the highest part of W, then, H is 0xf134. I understand the processor receives, from the memory, a word with the short
shifted:
{34, f1, 00, 00}
因为 0x0000f134 等于 0xf134.
since 0x0000f134 equals 0xf134.
考虑到这张图片,既然处理器有 4 字节长,因此无论如何都需要移位,为什么 2 字节数据必须在 2 字节字边界内对齐?
With this picture in mind, since the processor is 4-bytes long and it is thus neccesary by all means a shifting, why must 2-bytes data to be aligned in 2-bytes word boundaries?
换句话说:
为什么令人鼓舞建议不要阅读单词中的short
0xf134:
Why is encouragingly recommended not to read the short
0xf134 in the word:
{ff, 34, f1, 0a}
?
EDIT:表达同样疑问的另一种方式是:为什么对齐的定义是
EDIT: Other way of expressing the same doubt is: why the definition of alignment is
A object of size N and address d is aligned if d is divisible by N.
而不是:
A object of size N and direction d is aligned respect to an architecture
of B bytes if d is divisible by B, or ⌊d/B⌋ == ⌊(d+N)/B⌋ if N < B.
?
注意:属性 ⌊d/B⌋ == ⌊(d+N)/B⌋ 暗示该对象属于对齐的单词.
NOTE: The property ⌊d/B⌋ == ⌊(d+N)/B⌋ implies the object belongs to an aligned word.
推荐答案
如果内存是 { ff, 34, f1, 0a },那么对于 x86 处理器来说不是问题.但是,如果内存为 { ff, ff, ff, 34 } {f1, aa, aa, aa },则处理器必须执行两个总线周期才能检索 short 的值.(另请注意,有些基于 RISC 的处理器根本不支持未对齐访问.)
If the memory is { ff, 34, f1, 0a }, then it's not a problem for an x86 processor. However, if the memory is { ff, ff, ff, 34 } {f1, aa, aa, aa }, the processor must perform two bus cycles to retrieve the value of the short. (Also note there are some RISC-based processors that do not support misaligned accesses at all.)
这篇关于读取 32 位架构中的 Shorts(例如)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!