gpt4 book ai didi

c - 内存对齐公式

转载 作者:行者123 更新时间:2023-12-01 16:41:58 25 4
gpt4 key购买 nike

在浏览一些内核代码时,我发现内存对齐的公式为

aligned = ((operand + (alignment - 1)) & ~(alignment - 1))



然后我什至为此编写了一个程序:
#include <stdio.h>

int main(int argc, char** argv) {
long long operand;
long long alignment;
if(argv[1]) {
operand = atol(argv[1]);
} else {
printf("Enter value to be aligned!\n");
return -1;
}
if(argv[2]) {
alignment = strtol(argv[2],NULL,16);
} else {
printf("\nDefaulting to 1MB alignment\n");
alignment = 0x100000;
}
long long aligned = ((operand + (alignment - 1)) & ~(alignment - 1));
printf("Aligned memory is: 0x%.8llx [Hex] <--> %lld\n",aligned,aligned);
return 0;
}

但我完全不明白这个逻辑。这是如何运作的?

最佳答案

基本上,公式增加一个整数operand (address) 到与 alignment 对齐的下一个地址.

表达方式

aligned = ((operand + (alignment - 1)) & ~(alignment - 1))

基本上是一样的有点容易理解的公式:
aligned = int((operand + (alignment - 1)) / alignment) * alignment

例如,操作数(地址)为 102,对齐为 10,我们得到:
aligned = int((102 + 9) / 10) * 10
aligned = int(111 / 10) * 10
aligned = 11 * 10
aligned = 110

首先我们添加地址 9并获得 111 .然后,由于我们的对齐是 10,基本上我们将最后一位数字清零,即 111 / 10 * 10 = 110
请注意,对于 10 的每个次方对齐(即 10、100、1000 等),我们基本上将最后一位数清零。

在大多数 CPU 上,除法和乘法运算比按位运算花费的时间要多得多,所以让我们回到最初的公式:
aligned = ((operand + (alignment - 1)) & ~(alignment - 1))

只有当对齐是 2 的幂时,公式的第二部分才有意义。例如:
... & ~(2 - 1) will zero last bit of address.
... & ~(64 - 1) will zero last 5 bits of address.
etc

就像将地址的最后几位清零以进行 10 次幂对齐一样,我们将最后几位清零以进行 2 次幂对齐。

希望它现在对你有意义。

关于c - 内存对齐公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45213511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com