Search code examples
assembly

Adding 2 numbers in assembly x86


When you try to add 2 numbers it says a letter or a symbol

.plus:
                mov eax, [num1]
                sub eax, 0
                mov ebx, [num2]
                sub ebx, 0
                add eax, ebx
                sub eax, 0
                mov [num3], eax
                jmp .result

I was expecting to write 2 at 1 + 1 but it sayed b.


Solution

  • When you key in 1, your program receives 49 which is the ASCII that belongs to the character "1". Somehow you already knew that you would have to translate this character code into the value for the decimal digit. A subtraction of 48 (the difference between 49 and 1) was in order, but sadly you wrote sub eax, 0 instead of the required sub eax, 48 which we prefer to write as sub eax, '0' using the single quotation marks.

    Because of the above, the sum add eax, ebx was calculating 49 + 49 that produced 98 which happens to be the ASCII for the small caps character 'b'.

    While the conversion from ASCII to number [0,9] needs subtracting 48, the conversion from number [0,9] to character needs adding 48. You erroneously used a subtraction there too!

    movzx eax, byte [num1]  ; ['0','9']
    sub   eax, '0'          ; -> [0,9]
    movzx ebx, byte [num2]  ; ['0','9']
    sub   ebx, '0'          ; -> [0,9]
    add   eax, ebx          ; -> [0,9] hopefully ?
    add   eax, '0'          ; -> ['0','9']
    mov   [num3], al        ; ['0','9']
    

    That final add eax, '0' conversion is only correct if the addition produces a sum in the range [0,9]. Obviously if the sum is bigger than 9 you have to deal with a 2-digit result in the range [10,18].