Word conversion code: ASCII to Hexadacimal

section .data
message db "Enter a word of HEXADECIMAL VALUE ",10 ;Declare a message
message_length equ $-message                         ;Store length of message


section .bss

%macro PRINT 2 ;PRINT macro, This macro will take 2 parameters
mov rax,1
mov rdi,1
mov rsi,%1 ;Source to print
mov rdx,%2 ;Length of what to print
syscall
%endmacro

%macro READ 2 ;READ macro, This macro will take 2 parameters
mov rax,0
mov rdi,0
mov rsi,%1 ; Soucre: Where to store read value
mov rdx,%2 ;How many characters to be read + 1 (enter key)
syscall
%endmacro



counter resb 1
read_ascii resb 2 ;this will store the read value
converted_hex resb 1 ;this will store converted hexadecimal value

section .text
global _start
_start:

PRINT message,message_length ;Print the message
READ read_ascii,5                 ;Read the vaule 5= 4 characters to be read+ 1(enter key)

mov rsi,read_ascii                  ;Give source (value t0 be converted)
mov rdi,converted_hex          ;Give destination to store result
CALL ASCII_HEX ;Call the conversion Procedure

mov rax,60                   ;EXIT
mov rbx,0
syscall


ASCII_HEX:
xor bx,bx         ;bx will store the result. So,initializing rbx with zero
mov byte[counter],4         ;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 bx,4         ;Rotaton is needed for storing new converted value which is of 4 bits
add bl,al         ;Store in bx
inc rsi ;Point to next character
dec byte[counter] ;Decrement Counter
jnz loop         ;If Counter!=0 jump to loop label
mov word[rdi],bx ;Store result in destination
RET         ;Return

No comments:

Post a Comment