找到下一个对齐的内存地址

时间:2016-07-14 18:06:06

标签: c++ bit-manipulation memory-alignment

根据我对wikipedia的理解,我可以通过以下按位操作找到具有正确对齐的下一个最接近元素的索引。

Assuming the address of the 1st element has the correct alignment.
Assuming the index_alignment is a power of 2.
new_index = (current_index + index_alignment - 1) & ~(index_alignment - 1).
new_address = address_of_1st_element + new_index
index_alignment is 16 bytes/sizeof(type of element) for SSE.

是否可以直接在地址上使用它来查找任何给定地址中下一个最接近的对齐地址? (这样更快吗?)

我正在考虑以下事项来快速完成这项工作。

new_address = (current_address + alignment - 1) & ~(alignment -1)
alignment here is 16 for SSE.

当我实现这个时,我发现以下代码无法编译......

使用Salva和Rotem的建议修改了代码

#include <iostream>
#include <stdint.h>
#define ALIGNMENT 16
using namespace std;
uint32_t* fix_ptr(uint32_t* ptr){
    return (uint32_t*)(
        (uintptr_t(ptr) + uintptr_t(ALIGNMENT) - 1)
        &~ uintptr_t(ALIGNMENT - 1)
        );
}
void print_ptr (uint32_t* ptr){
    cout << (long long)(void*)ptr << endl;
}

void test(uintptr_t ptr_as_int){
    uint32_t* ptr1 = (uint32_t*) ptr_as_int;
    cout << "Initial address: ";
    print_ptr(ptr1);
    uintptr_t alignment = ALIGNMENT;
    cout << "    alignment: " << alignment << endl;
    cout << "    alignment - 1: " << (alignment - 1) << endl;
    cout << "    alignment & alignment: " << (alignment & alignment) << endl;

    uint32_t* ptr_fixed = fix_ptr(ptr1);
    cout << "    fixed address: ";
    print_ptr(ptr_fixed);
}
int main(void){
    test(1000);
    test(16);
}

输出(使用g ++ code.cpp编译)

Initial address: 1000
    alignment: 16
    alignment - 1: 15
    alignment & alignment: 16
    fixed address: 1008
Initial address: 16
    alignment: 16
    alignment - 1: 15
    alignment & alignment: 16
    fixed address: 16

1000变为1008,16变为16。我目前的使用可能还可以。不知道是否有更快的方法。

感谢。

0 个答案:

没有答案