How to convert a binary number into decimal and show the answer in 3 digits?

48 views Asked by At

I have this piece of code from my project. It is taking all the amount from the transaction and adding it and showing how much you earned in the day. The problem is it's not showing in decimal format and if it's showing 3 digit number or not.

Conclusion is I want it to show 3 digit number and in decimal format.

show_amount:
    mov     dx, offset amount_earned
    mov     ah, 9
    int     21h

    mov     ax, 00h
    mov     al, amount
    AAM
    mov     ch, ah
    mov     cl, al

    add     ch, 48   ; Convert the first digit to ASCII decimal
    add     cl, 48   ; Convert the second digit to ASCII decimal

    mov     dl, ch
    mov     ah, 2
    int     21h

    mov     dl, cl
    mov     ah, 2
    int     21h

    cmp     dl, 48   ; Check if the number is less than 100
    jl      skip_zero
    mov     dl, 48   ; If it's 100 or more, set the first digit to 0
    mov     ah, 2
    int     21h

skip_zero:
    add     dl, 48   ; Convert the number to ASCII decimal
    mov     ah, 2
    int     21h

    mov     dl, 0    ; Move 0 to DL register for decimal conversion
    mov     ah, 2
    int     21h

    jmp     start    

I have tried the above code where the total transaction was 72+72=144 but it's showing:

>40` 
1

There are 1 answers

1
Sep Roland On

About aam instruction: see AAM Instruction in EMU8086.

Loading your example amount of 144 in the AL register (no need to zero AX beforehand), the aam instruction will divide AL by 10, store the remainder (4) in AL and store the quotient (14) in AH. For the remainder there's no problem since it is in range [0,9] and you can add 48 to turn it into a decimal character. But if you apply the same addition to the quotient that is greater than 9 and so out-of-range, you get the non-sense '>' character.
The part of your code that follows and that (tries to) produce a third character then comes too late as by then you have already displayed the units digit.

To solve this task you need to perform aam twice. The second time you need to apply it to the quotient that you got the first time.

  mov  al, amount  ; 1st time
  aam              ; 144 / 10 -> quotient AH=14, remainder AL=4
  add  al, '0'
  push ax          ; (1)

  mov  al, ah      ; 2nd time using quotient from 1st time
  aam              ; 14 / 10 -> quotient AH=1, remainder AL=4
  add  ax, '00'
  mov  cx, ax      ; -> CH="1"  CL="4"

  mov  ah, 02h     ; DOS.PrintCharacter
  mov  dl, ch
  int  21h         ; -> AL = DL = "1"
  mov  dl, cl
  int  21h         ; -> AL = DL = "4"
  pop  dx          ; (1)
  int  21h         ; -> AL = DL = "4"