Reputation: 11
I am trying to sum two hex numbers in Assembly x8086, each one with one digit. I know how to sum decimals. Can someone show me how to do that? Here is my code:
ADD CL, BL ; CL and BL have the one digit numbers
MOV AL, CL
MOV AH, 0
AAA
ADD AX, 3030H
MOV BX, AX
mov dl, bh
call mostrarchar
mov dl, bl
call mostrarchar
int 20H
Nomeprog ENDP
mostrarchar proc near
mov AH, 02h
int 21h
ret
mostrarchar endp
Upvotes: 0
Views: 3857
Reputation: 10381
As suggested by Margaret Bloom, you need your proc mostrarchar
to detect when the number is less or equal to 9 (it's a digit) and when the number is greater than 9 (it's a letter, 10..15 = 'A'..'F'), example :
mov dl, 8
call mostrarchar ;DISPLAY '8'.
mov dl, 15
call mostrarchar ;DISPLAY 'F'.
mostrarchar proc
cmp dl, 9
jbe digit ;IF ( DL <= 9 )
;IT'S A LETTER (10..15 = 'A'..'F').
add dl, 37h ;DL+55.
jmp display ;SKIP "DIGIT:".
digit:
add dl, 30h ;DL+48.
display:
mov ah, 02h
int 21h
ret
mostrarchar endp
Previous code works for one digit only. For bigger numbers, you will need to divide the number by the base (in your case, base 16) several times until it becomes zero, each remainder is one digit, then you call mostrarchar
to display each hex digit, example:
mov ax, 15729
call mostrarnum ;DISPLAY '3D71'.
mostrarnum proc
;CONVERT NUMBER TO HEX.
mov bp, 16 ;BASE.
mov cx, 0 ;REMAINDERS COUNTER.
divisions:
mov dx, 0
div bp ;DX:AX ÷ 16.
push dx ;PUSH REMAINDER.
inc cx ;COUNT REMAINDER.
cmp ax, 0
jne divisions ;IF ( AX != 0 )
;DISPLAY HEX DIGITS EXTRACTED FROM NUM.
remainders:
pop dx
call mostrarchar ;DISPLAY HEX CHAR.
loop remainders ;CX-1. IF ( CX > 0 ) REPEAT.
ret
mostrarnum endp
Proc mostrarnum
first converts the number into hex by extracting digits with succesive divisions. This digits are stored in stack with push
. Finally, the digits are retrieved from stack and displayed. This is necessary because the divisions generate the digits in reverse order, by pushing the digits in stack they are reversed again, so, when they come out, they are in normal order.
The addition of numbers don't care about the base (binary, decimal, hex, etc.), numbers, as dwelch said, are just bits, it's you, as human being, who decides if those bits are hex or decimal, etc. Examples :
mov al, 9 ;DECIMAL.
mov ch, 0Ah ;10
add ch, al ;0Ah + 9 = 13h (19)
mov dl, 01110011b ;BINARY (115, 73h)
add ch, dl ;13h + 115 = 134 (86h)
You can display the final result as decimal ("134"), hex ("86") or any other.
By the way, you can use the same technique (succesive divisions by a given base) to convert to any base, for example, dividing by 8 will give you octal, and dividing by 14 will give you ... base 14.
Upvotes: 2