Scene:
1. Some frequently used pointer variable address is not aligned, running efficiency and alignment efficiency is very different, so in the creation of heap space, it is necessary to the memory address alignment to improve operational efficiency.
2. Some audio and video processing codes or custom malloc are basically address-aligned.
3. When using an atom-accessible interlock function, the InterlockedExchangeAdd requires an address alignment.
4. The main or macro apr_align, which is said to be the Apache source, just borrow it.
Solution:
1. In fact, it is to let the address value of the alignment of the modulus of 0, the address value of the maximum increase of n-1 offset address can be the entire n. &~ (n-1) is a quick way to divide N, which is equivalent to moving the number of digits to the left by 2.
#include < iostream> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> Using namespace std;//apache/* apr_align () is only to being used to ALIGN on a power of 2 boundary */#define APR_ALIGN (Size, Boundary) (((size) + (((boundary)-1)) & ~ ((boundary)-1)) void Testalgin () {//1.32-byte alignment. To align addresses, you will typically create extra space to align .//1. You need to create 16 bytes of space if you need 32-byte alignment. uint8_t* value = (uint8_t*) malloc (16+32); cout << "1" << (int64_t) (int64_t*) (value) << endl;int64_t* value_offset = (int64_t*) apr_align ((int64_t) (int64_t*) value,32) cout << "2" << ( int64_t) (int64_t*) (value_offset) << endl;//1. Test custom 4-byte alignment, the source address is 5, the final address is 8.int64_t v1 = apr_align (5,sizeof (int32_t)); assert (V1 = = 8);//1. Test the Custom 8-byte alignment, the original address is 10, the final address is 16v1 = Apr_align (10,sizeof (int64_t)); assert (V1 = = 16);} int main (int argc, char const *argv[]) {testalgin (); return 0;}
Output:
1 63144802 6314496
Reference:
http://bbs.csdn.net/topics/370085011
Http://bbs.chinaunix.net/thread-1233919-1-1.html
The 4th edition of Windows core programming
[c/c++]_[Intermediate]_[data address alignment]