3

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
Bewn
  • 575
  • 4
  • 9
  • 13
  • related: http://stackoverflow.com/questions/4953506/why-does-my-code-display-rubbish/4954659#4954659 and another: http://stackoverflow.com/questions/9113060/print-decimal-in-8086-emulator – Jens Björnhager Feb 02 '12 at 14:27

2 Answers2

9

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
PauliL
  • 1,259
  • 9
  • 7
  • 1
    At line 'push dx', do you actually mean push edx? I'm unfamiliar with Intel syntax, so I'm confused. It would be logical to push the remainder, edx, to the stack. – cvbattum Oct 21 '16 at 15:17
  • 1
    @Creator13: `dx` is the low 16 bits of `edx`. This code is using 16-bit operand-size to save stack space. (And for no reason at all with the `bx` and `cx` counters.) Also, if you're just storing into a buffer, you can start at the end of the buffer and decrement a pointer. Copy to the front later if needed. – Peter Cordes Apr 26 '20 at 21:26
5

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.

Nishant
  • 20,354
  • 18
  • 69
  • 101
dbrank0
  • 9,026
  • 2
  • 37
  • 55