section .data
prompt db "Hexdecimal value : ", 0
hex_digits db "0123456789ABCDEF"
section .bss
input resb 4 ; To store 2 digits + newline + null
outbuf resb 3 ; 2 hex digits + newline
section .text
global _start
_start:
; -------- Prompt user --------
mov rsi, prompt
call print_string
; -------- Read input --------
mov rax, 0 ; sys_read
mov rdi, 0 ; stdin
mov rsi, input
mov rdx, 4
syscall
; -------- Convert ASCII to integer --------
; input = "42\n"
movzx rax, byte [input] ; first digit
sub rax, '0'
imul rax, 10
movzx rcx, byte [input + 1] ; second digit
sub rcx, '0'
add rax, rcx ; rax now has decimal number
; -------- Convert to Hexadecimal --------
; High nibble
mov rcx, rax
shr rcx, 4
and rcx, 0xF
movzx rdx, byte [hex_digits + rcx]
mov [outbuf], dl
; Low nibble
mov rcx, rax
and rcx, 0xF
movzx rdx, byte [hex_digits + rcx]
mov [outbuf+1], dl
; Newline
mov byte [outbuf+2], 10
; -------- Print Hex --------
mov rax, 1 ; sys_write
mov rdi, 1 ; stdout
mov rsi, outbuf
mov rdx, 3
syscall
; -------- Exit --------
mov rax, 60 ; sys_exit
xor rdi, rdi
syscall
; ------------------------------------------------
; print_string: prints null-terminated string at RSI
; ------------------------------------------------
print_string:
push rsi
xor rcx, rcx
.count:
cmp byte [rsi + rcx], 0
je .done
inc rcx
jmp .count
.done:
mov rax, 1 ; sys_write
mov rdi, 1 ; stdout
pop rsi
mov rdx, rcx
syscall
ret
To embed this project on your website, copy the following code and paste it into your website's HTML: