This is my best effort at converting a 32 bit integer in EAX
, to an 8 character ascii string (result in RDI
). It will work accurately up to 99,999,999. Higher values could be done using an xmm
register. The byte order in RDI
is correct (e.g. if copied directly to video ram, the most significant byte is displayed first) No expensive DIV
instructions or memory accesses required. Can this be improved further?
mov ebx, 0xCCCCCCCD
xor rdi, rdi
.loop:
mov ecx, eax ; save original number
mul ebx ; divide by 10 using agner fog's 'magic number'
shr edx, 3 ;
mov eax, edx ; store it back into eax
lea edx, [edx*4 + edx] ; multiply by 10
lea edx, [edx*2 - '0'] ; and ascii it
sub ecx, edx ; subtract from original number to get remainder
shl rdi, 8 ; shift in to least significant byte
or rdi, rcx ;
test eax, eax
jnz .loop