Friday, April 1, 2016

POST 3:ASCII to HEXADECIMAL CONVERSION

Hello everyone!
In this blog I will be discussing about conversion of ASCII values to HEXADECIMAL value.

Why do we need this conversion?
The characters that we give as input from the keyboard are read in the format of ASCII system.
For performing various operations like addition,multiplication,division and subtraction we need to use HEXADECIMAL equivalent of those numbers.

Consider  addition of  2 and 3.
ASCII value of 2 is 32h and that of 3 is 33h.
So, if we add these two numbers without conversion, we get 32h+ 33h =65h.
But ASCII equivalent of our expected answer 2+3=5 is 35h.
As you can see this gives us wrong answer.

Now if we convert these numbers before any operation we will get correct answer.
e.g.
2+ 3
HEXADECIMAL equivalent of 2 is 02h and that of 3 is 03h.
After addition, 02h + 03h = 05h we get correct answer.
And to print the answer we convert i back to ASCII value i.e. 35h.

Here is the routine for BYTE conversion of ASCII to HEX:


ASCII_HEX:
xor bl,bl ;bl will store the result. So,initializing rbx with zero
mov byte[counter],2 ;counter = number of characters to convert
loop: ;loop label
mov al,byte[rsi] ;Take the byte of value to be converted
cmp al,39h ;Refer ASCII table. This is needed for deciding value of character between (0 to 9) or (A to F)
jbe sub_30 ;If character<39 it is between 0 to 9. So,subtract only 30 from it
sub al,0x07 ;If character>39 it is between A to F. So,subtract only 7 + 30 from it
sub_30:
sub al,0x30 ;Now al contains converted value read from rsi
rol bl,4 ;Rotation is needed for storing new converted value which is of 4 bits
add bl,al ;Store in bl
inc rsi ;Point to next character
dec byte[counter] ;Decrement Counter
jnz loop ;If Counter!=0 jump to loop label
mov byte[rdi],bl ;Store result in destination
RET ;Return


Here, each character occupies one byte in its ASCII format. After conversion,it takes 4 bits to represent it in HEX format (0 to F)


The main logic that might be difficult to understand is comparison with 39 and the subtraction of 30 and 07. For this refer to ASCII table.
Here comparison with 39 decides whether number is between 0 to 9 or A to F.


CLICK HERE FOR BYTE CONVERSION

CLICK HERE FOR WORD CONVERSION



No comments:

Post a Comment