I'm working with a program in assembly using the at&t syntax on an intel.
I'm lost, how do I convert an integer in a register to an ascii number?
Lets say I want to convert the number 10 and I will put the number 10 in register %eax. If i just add the number 48 to %eax, the ascii sign will be a :
I want to add 48 to the 1, and then 48 to the 0 in the number 10. How can i do that?
Sample code:
mov $10, %eax
#Cut the number in some way.
add $48, %eax
To convert number into ASCII, you need to divide the number by 10 and use the remainder as result. Then add ASCII '0' and store the resulting digit. Then repeat the same with the quotient until it reaches zero.
However, this gives the digits in reverse order, starting from the least significant digit. You can reverse the order for example by using stack. Push each digit into stack, then pop them and store into a string buffer.
Something like this (not tested):
.DATA
strResult db 16 dup (0) ; string buffer to store results
.CODE
mov eax, number ; number to be converted
mov ecx, 10 ; divisor
xor bx, bx ; count digits
divide:
xor edx, edx ; high part = 0
div ecx ; eax = edx:eax/ecx, edx = remainder
push dx ; DL is a digit in range [0..9]
inc bx ; count digits
test eax, eax ; EAX is 0?
jnz divide ; no, continue
; POP digits from stack in reverse order
mov cx, bx ; number of digits
lea si, strResult ; DS:SI points to string buffer
next_digit:
pop ax
add al, '0' ; convert to ASCII
mov [si], al ; write it to the buffer
inc si
loop next_digit
Generally you can do it this way:
repeat
d = x MOD 10
x = x DIV 10
stringd = d + 48;
store character somewhere
until x == 0
print characters in reverse order
But digits will be from last to first. Convert this to assembly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With