全部博文(130)
分类: LINUX
2013-10-20 15:32:30
The following formulas provide the number of padding bytes required to align the start of a data structure (where mod is the modulo operator):
# pseudo-code, see actual code below padding = (align - (offset mod align)) mod align new offset = offset + padding = offset + (align - (offset mod align)) mod align
For example, the padding to add to offset 0x59d for a structure aligned to every 4 bytes is 3. The structure will then start at 0x5a0, which is a multiple of 4. Note that when offset already is a multiple of align, the second modulo in (align - (offset mod align)) mod align is required to get a padding of 0.
If the alignment is a power of two, the modulo operation can be reduced to a bitwise boolean AND operation. The following formulas provide the new offset (where& is a bitwise AND and ~ a bitwise NOT):
padding = align - (offset & (align - 1)) = (-offset) & (align - 1) new offset = (offset + align - 1) & ~(align - 1)