When I add two values in 16 bit assembly, what is the best way to print the result to console?
At the moment I have this code:
;;---CODE START---;;
mov ax, 1 ;put 1 into ax
add ax, 2 ; add 2 to ax current value
mov ah,2 ; 2 is the function number of output char in the DOS Services.
mov dl, ax ; DL takes the value.
int 21h ; calls DOS Services
mov ah,4Ch ; 4Ch is the function number for exit program in DOS Services.
int 21h ; function 4Ch doesn't care about anything in the registers.
;;---CODE END---;;
I think that dl value should be in ASCII code, but I'm not sure how to convert ax value after addition into ASCII.
This won't work as
dl
andax
have different bit sizes. What you want to do is create a loop in which you divide the 16 bit value by 10, remember the rest on the stack, and then continue the loop with the integer division result. When you reach a result of 0, clean up the stack digit by digit, adding 48 to the digits to turn them into ASCII digits, then print them.Just fixing the order of @Nathan Fellman 's code
You basically want to divide by 10, print the remainder (one digit), and then repeat with the quotient.
As a side note, you have a bug in your code right here:
You put
2
inah
, and then you putax
indl
. You're basically junkingax
before printing it.You also have a size mismatch since
dl
is 8 bits wide andax
is 16 bits wide.What you should do is flip the last two lines and fix the size mismatch:
The basic algorithm is:
Note that this will yield the digits in the inverse order, so you are probably going to want to replace the "emit" step with something that stores each digit, so that you can later iterate in reverse over the stored digits.
Also, note that to convert a binary number between 0 and 9 (decimal) to ascii, just add the ascii code for '0' (which is 48) to the number.