Search code examples
assemblyadditionsubtractioninstructions

Why sub eax, '0' for adding instead of just add?


So, I've been trying to learn some assembly and I saw an example of an addition but I don't really understand one thing:

section .text
    global _start       
_start:                     
    mov eax, '3'
    sub eax, '0'
    mov ebx, '4'
    sub ebx, '0'
    add eax, ebx
    add eax, '0'
    mov [sum], eax
    mov ecx, msg
    mov edx, len
    mov ebx, 1
    mov eax, 4
    int 0x80
    mov ecx, sum
    mov edx, 1
    mov ebx, 1
    mov eax, 4
    int 0x80
    mov eax, 1
    int 0x80
section .data
msg db  'The sum is:',0xA, 0xD
len equ $ - msg 
segment .bss
sum resb

I understand all except for the sub eax, '0'

I mean the result should be -7 because when it does sub eax, '0' it inverses the number...


Solution

  • ... because when it does sub eax, '0' it inverses the num

    The subtraction sub eax, '0' converts the character in AL into the corresponding number 0-9. Nothing more.

    It should have been written:

    sub al, '0'
    

    In the same manner will the instruction add al, '0' convert the number in AL (in the range 0-9) into a character that's ready for outputting.


    I mean the result should be -7

    If you run the program, you'll see that the output will be a positive 7.