At the time of storage, in order to improve the efficiency, the offset is usually placed in the position of 2 m, and it is often rounded up and down to take the whole two requirements.
Rounding down
Palign_down (X,align) (X & (-align))
Why do you do this, because align or oneself, only the high point all become 1, and then the original number & operation, at this time not more than 1 are cleared 0.
PALIGN_UP (X,align) (-(x) & (-align))
The principle is also relatively easy to infer, the X into a negative, then to-X down to reverse, the resulting number is reversed negative, but with a minus sign, negative positive, get a larger integer
To achieve an upward rounding.
Equivalent to Palign_up (x,align) =====>-palign_down (-x,align)
Palign_down Down Rounding Example:
42 Binary:
0000 0100
1111 1100
If X is 3, 011, and-align and after 0
If X is 5,101, then it is 4.
An article:
Memory alignment Algorithms
Byte alignment is an issue to consider when allocating memory, two small algorithms:
(1) The most easily thought out algorithm:
- unsigned int calc_align (unsigned int n,unsigned align)
- {
- if (n/align * align = = n)
- return n;
- return (n/align + 1) * ALIGN;
- }
(2) Better algorithms:
- unsigned int calc_align (unsigned int n,unsigned align)
- {
- return ((n + align-1) & (~ (align-1)));
- }
For the 2 algorithm the principle is as follows:
2-byte alignment, requires the address bit to be 2,4,6,8 ..., bits the last one is 0 (2 of 1) 4 byte alignment, requires address bit 4,8,12,16 ..., bits last two bits 0 (2 2) 8 byte alignment, requires address bit 8, 16,24,32., requires bits last three bits 0 (2 of 3) 16 byte alignment, requires address bit 16,32,48,64 ..., bits last four bits 0 (2 of 4) ... This shows that we just need to align the data to the minimum required data, and then the completion of position 0 can be achieved alignment calculation. (1) (align-1), which indicates the alignment of the required alignment bits, such as: 2-byte alignment of 1, 4 bytes is 11, 8 bytes is 111, 16 bytes is 1111 ... (2) (x+ (align-1)), which indicates that X is aligned with the required data (3) &~ (align-1), which means to remove redundant data due to the completion (4) (x+ (align-1)) &~ (align-1), which represents the aligned data For example: 8-byte alignment. Starting at the beginning is the 0000 + (8-1) =0000 0110 + 0000 0111 = 0000 11010000 1101 & ~ (0111) = 0000 1000//Remove redundant data due to completion
2 m-Square memory alignment