Domanda

I know you can add 48 to convert from decimal to ascii or subtract 48 to convert from ascii to decimal, but why does the following code also perform this same conversion?

; moving the first number to eax register and second number to ebx
; and subtracting ascii '0' to convert it into a decimal number
mov eax, [number1]
sub eax, '0'

and

; add '0' to to convert the sum from decimal to ASCII
add eax, '0'
È stato utile?

Soluzione

The '0' works identically to 48 because '0' is the code point for the character 0 which, in ASCII, is indeed 48.

Hence all of these are equivalent:

sub  al, 48          ; decimal
sub  al, '0'         ; character code
sub  al, 30h         ; hex
sub  al, 0x30        ; hex again
sub  al, 60q         ; octal
sub  al, 00110000b   ; binary

An keep in mind that this method only works for a value from 0 to 9 inclusive. If you want to handle values above nine, you'll need to decompose the value into individual digits and process them one at a time.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top