8051 bcd 24 bits conversion
; Dear 8051 users,
; This is a simple algorithm and its 8051 microcontroller implimentation
; to convert binary to BCD .
; Modifications to my code is highly welcomed. If you make changes to this code
; please post here.
; This alorithm I got from following forum
; ------- Date: 19970630
; ------- From: Brian Trial
; ------- To:
Mot-68HC11-Apps@freeware.mcu.motsps.com
; ------- Subject: Re: Simpler method to output 24bits in decimal
; 1. Add 3 to every BCD nibble that's >=5
; 2. Shift left
; Repeat until binary portion is all 0000
;
; Example: Convert $F9 to BCD
;
; 0000 0000 0000 : 1111 1001
; 0000 0000 0001 : 1111 0010 (shift left)
; 0000 0000 0011 : 1110 0100 (shift left)
; 0000 0000 0111 : 1100 1000 (shift left)
; 0000 0000 1010 : 1100 1000 (add 3)
; 0000 0001 0101 : 1001 0000 (shift left)
; 0000 0001 1000 : 1001 0000 (add 3)
; 0000 0011 0001 : 0010 0000 (shift left)
; 0000 0110 0010 : 0100 0000 (shift left)
; 0000 1001 0010 : 0100 0000 (add 3)
; 0001 0010 0100 : 1000 0000 (shift left)
; 0010 0100 1001 : 0000 0000 (shift left)
;
; And the left now holds BCD 249.
; MUCH easier than messing with IDIV and FDIV!!!
; -------------------------------------------------
; 8051 microcontroller implimentation by
; itp ( an elektroda eboard member)
org data_segment ; inernal data
bin_val: ds 2 ; 16 bit bin value to be converted
bcd_val: ds 3 ; converted 5 digit packed bcd
org code_segment ; code starts here
; 16 bit binary to bcd conversion.
bin2bcd:
push acc
push psw
mov psw,#08h ; select register bank 1
mov r0,#bin_val
mov r1,#bcd_val+2
clr a
mov @r1,a
dec r1
mov @r1,a
dec r1
mov @r1,a
mov r3,#16 ; for 16 bit
again1:
call adj_bcd
mov r0,#bin_val
mov r1,#bcd_val
clr c ; shift the bytes
mov a,@r0
rlc a
mov @r0,a
inc r0
mov a,@r0
rlc a
mov @r0,a
mov a,@r1
rlc a
mov @r1,a
inc r1
mov a,@r1
rlc a
mov @r1,a
inc r1
mov a,@r1
rlc a
mov @r1,a
inc r1
mov a,@r1
rlc a
mov @r1,a
inc r1
mov a,@r1
rlc a
mov @r1,a
skipx:
djnz r3,again1
exit:
pop psw
pop acc
ret
adj_bcd:
mov r1,#bcd_val
mov b,#3
again:
mov a,@r1
mov r7,a
anl a,#0fh
cjne a,#5,ok ; a >= 5 ?
ok:
jc skip ; if yes add 3
add a,#3
skip:
mov @r1,a
mov a,r7
anl a,#0f0h
swap a
cjne a,#5,ok1
ok1:
jc skip1
add a,#3
skip1:
swap a
add a,@r1
mov @r1,a
inc r1
djnz b,again
ret
-------------------------------------
/* C example for binary to bcd conversion*/
/* This uses different algoritham */
unsigned int bintobcd(unsigned int binvalue)
{
unsigned char j=0;
unsigned int h=0;
do
{
h += ((binvalue%10)<<j);
binvalue = binvalue/10;
j += 4;
}
while(binvalue >= 10);
h += ((binvalue) << j);
return h;
}