Assembly code snippets

Back to the snippets overview


TitleBuffer Alignment Calculator
Submitted by:TDCNL
Date added:2006-02-19 10:59:35
Date modified:2006-02-19 10:59:35


I wrote this little routine to easily calculate the needed alignment, for example if you have a buffer of 23 bytes (for some user input or so), and you want to align all data that is defined after that buffer of 23 bytes, say, you want to align that by dword (4 bytes), then AlignCalculate will return 1, because 23 / 4 = 5, rest 3, then, 4-3 is 1. The little calculation is "Needed alignment = AlignmentSize - (BufferSize / AlignmentSize)"

Most users of course recognize numbers divisible by 4, but sometimes it can be a handy tool, I just wrote it for knowledge and some fun to learn new instructions, because before I never used CMOVx instructions.

Greetz, TDCNL


AlignCalculate PROC AlignmentSize:DWORD,BufferSize:DWORD
;requirement: 686 processor instructions
;eax = BufferSize
;ebx = AlignmentSize
;Needed alignment = AlignmentSize - (BufferSize / AlignmentSize)
;return value is in register eax, if eax is zero, no alignment was needed
;otherwise, eax is the required size to align with
mov ebx,AlignmentSize
mov eax,BufferSize
idiv    ebx
mov dword ptr[BufferSize],0
lea ebx,BufferSize
test    edx,edx
cmovz   eax,dword ptr[ebx]
jz  @F
mov eax,AlignmentSize
sub eax,edx
AlignCalculate ENDP