C语言 如何检查内存地址是否在 C 中对齐 32 位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19190502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:37:47  来源:igfitidea点击:

How Do I check a Memory address is 32 bit aligned in C

cmemorymemory-managementlinux-kernel

提问by Amit Singh Tomar

My question has two parts.

我的问题有两个部分。

First, as a newbie to this address space, I would like to know what is the meaning of memory alignment of an address. I Googled about it but wanted to ask this question here as well since I found answers here very useful.

首先,作为这个地址空间的新手,我想知道一个地址的内存对齐是什么意思。我用谷歌搜索了一下,但也想在这里问这个问题,因为我发现这里的答案非常有用。

The second part of my question is related to alignment and programming: how do I find if an address is 4 byte aligned or not ? Somewhere I read:

我的问题的第二部分与对齐和编程有关:如何查找地址是否为 4 字节对齐?我在某处读到:

  if(address & 0x3) // for 32 bit register 

But I don't really know how this checks for a 4 byte alignment. Could anyone explain it in detail?

但我真的不知道这是如何检查 4 字节对齐的。谁能详细解释一下?

Edit: It would be great If someone can draw pictorial view on this subject.

编辑:如果有人可以在这个主题上绘制图形视图,那就太好了。

Thanks

谢谢

回答by lurker

Sequential addresses refer to sequential bytes in memory.

顺序地址是指内存中的顺序字节。

An address that is "4-byte aligned" is a multiple of 4 bytes. In other words, the binary representation of the address ends in two zeros (00), since in binary, it's a multiple of the binary value of 4(100b). The test for 4-byte aligned address is, therefore:

“4 字节对齐”的地址是 4 字节的倍数。换句话说,地址的二进制表示以两个零 ( 00)结尾,因为在二进制中,它是4( 100b)的二进制值的倍数。因此,对 4 字节对齐地址的测试是:

if ( (address & 0x3) == 0 )
{
    // The address is 4-byte aligned here
}

or simply

或者干脆

if ( !(address & 0x3) )
{
    // The address is 4-byte aligned here
}

The 0x3is binary 11, or a mask of the lowest two bits of the address.

0x3是二进制的11,或地址的最低两个比特的掩模。

Alignment is important since some CPU operations are faster if the address of a data item is aligned. This is because CPUs are 32-bit or 64-bit word based. Small amounts of data (say 4 bytes, for example) fit nicely in a 32-bit word if it is 4-byte aligned. If it is not aligned, it can cross a 32-bit boundary and require additional memory fetches. Modern CPUs have other optimizations as well that improve performance for address aligned data.

对齐很重要,因为如果数据项的地址对齐,某些 CPU 操作会更快。这是因为 CPU 是基于 32 位或 64 位字的。如果 32 位字是 4 字节对齐的,那么少量数据(例如 4 字节)就非常适合。如果未对齐,则可能跨越 32 位边界并需要额外的内存提取。现代 CPU 还具有其他优化功能,可以提高地址对齐数据的性能。

Here's a sample article regarding the topic of alignment and speed.

这是关于对齐和速度主题的示例文章。

Here are some some nice diagrams of alignment.

这里有一些很好的对齐图