Please disable adblock to view this page.

← Go home

Hex to BCD, BCD to Hex conversion (Assembly x86)

April 23, 2016
Published By : Pratik Kataria
Categorised in: ,

section .data
msg db 10,13,”Enter Hex number (max. FFFFH)”, 10
msglen equ $-msg

msg2 db 10,13,”The converted BCD number is:”, 10
msglen2 equ $-msg2

nwline db 10
nwlen equ $-nwline

msg3 db 10,13,”Enter BCD number: (Note: Enter 5 digit. E.g. 00018)”, 10
msglen3 equ $-msg3

msg4 db 10,”Choose one of the following:”, 10, “(1)Hex to BCD”, 10, “(2)BCD to Hex”, 10, “(3)Exit”, 10
msglen4 equ $-msg4

msg5 db 10,”The converted Hex number is:”, 10
msglen5 equ $-msg5

section .bss
cnt resb 1
num resb 5
num1 resb 1
num2 resb 6
numbuff resb 5
num3 resb 4
opt resb 1

%macro disp 2
mov eax,4
mov ebx,1
mov ecx,%1
mov edx,%2
int 80h

%macro accept 2
mov eax,3
mov ebx,0
mov ecx,%1
mov edx,%2
int 80h

section .text

global _start


disp msg4, msglen4
accept opt, 2

sub byte[opt], 30h

;mov eax, [opt]

cmp byte[opt], 01h
jz hextobcd
cmp byte[opt], 02h
jz bcdtohex
cmp byte[opt], 03h
jz exit

;–Hex to BCD–


disp msg, msglen

accept num, 5

call ascii_to_original

mov eax, 0
mov eax, ebx
mov cx, 10
mov byte[cnt], 00h

mov edx, 0
div cx
push dx        ;Pushing Remainder
inc byte[cnt]
cmp ax, 0
jnz l1

disp msg2, msglen2

pop dx
add dl, 30h
mov [num1], dl
disp num1, 1
dec byte[cnt]
jnz l6

disp nwline, nwlen

jmp _start

;–BCD to Hex–


disp msg3, msglen3

accept num2, 6

mov esi, num2
mov eax, 0        ;clear since it is used by default by mul instruction
mov ebx, 10       ;since we multiply 10 according to places. E.g. unit place -> *1 ten’s place -> *10 etc. and we add
mov ecx, 05       ;5 digit number max. (65,535)

mov edx, 0    ;before multiplication, initialize
mul ebx
mov edx, 0    ;To clear higher bytes since we are doing operaiton on dl
mov dl, [esi]
sub dl, 30h
add eax, edx
inc esi
dec ecx
jnz l5

mov [numbuff], eax

disp msg5, msglen5

call original_to_ascii

disp nwline, nwlen

jmp _start

;Example: 18 BCD to 12h Hex
;8*1 = 08 = 0000 1000
;      +
;1*10= 0A = 0000 1010
;        ———–
;        0001 0010

;For 18, it will be stored as: [30][30][30][31][38]
;Step by Step execution:

; (1) eax = 0 dl = 0
;     eax = 0

; (2), (3) same as above since 0 (30)

; (4) eax = 0 dl = 01
;     eax = 01

; (5) eax = 10 (i.e. 0A) dl = 08
;     eax = 12 (i.e. 00C0)


mov eax, 1
mov ebx, 0
int 80h

;–ASCII to Original–


mov edi,num
mov ecx,2
mov bx,0

rol bx,4
mov al,[edi]
cmp al,39h
jbe l3

sub al,07h

sub al,30h
mov ah,0h
add bx,ax
inc edi
loop l2


;–Original to ASCII–


disp nwline, nwlen

mov edi, numbuff
mov bx, [edi]
mov ecx, 5
mov esi, num3

rol bx, 4
mov dl, bl
and dl, 0fh
cmp dl, 09h
jbe l8
add dl, 07h

add dl, 30h
mov [esi], dl
inc esi
loop l7

disp num3, 4


View Article Page

Pratik Kataria is a budding programmer, web designer and developer.