Binary to BCD. By Lee Davison. |
Another one I'd not thought about until recently when I was asked if I had it. Here's what I eventually came up with....The code.I know it's almost a bit long for this section but it is the complement to the BCD to binary routine.
The byte to be converted is in A and the result is returned in low(/high) and A(/X). The bytes low and high can be anywhere but are probably best in page zero.If you know that the value to be converted lies in the range $00 to $63 (0 to 99 decimal) then all the code between the ***** lines can be omitted.
; table of BCD values for each binary bit, put this somewhere. ; note! values are -1 as the ADC is always done with the carry set b2b_table .byte $63,$31,$15,$07,$03,$01,$00 bin_2_bcd SED ; all adds in decimal mode STA low ; save A LDA #$00 ; clear A LDX #$07 ; set bit count bit_loop LSR low ; bit to carry BCC skip_add ; branch if no add ADC b2b_table-1,X ; else add BCD value skip_add DEX ; decrement bit count BNE bit_loop ; loop if more to do ;*********************************************************************** ; if you only require conversion of numbers between $00 and $63 (0 to 99 ; decimal) then omit all code between the "*"s BCC skip_100 ; branch if no 100's carry ; if Cb set here (and can only be set by the ; last loop add) then there was a carry into INX ; the 100's so add 100's carry to the high byte skip_100 ; now check the 2^7 (128) bit LSR low ; bit 7 to carry BCC skip_fin ; branch if no add INX ; else effectively add 100 part of 128 ADC #$27 ; and then add 128 (-1) part of 128 BCC skip_fin ; branch if no further carry INX ; else add 200's carry skip_fin STX high ; save result high byte ; end of 100's code ;*********************************************************************** STA low ; save result low byte CLD ; clear decimal modeThe two BCD digit version is $1C bytes long (assuming temp is in page zero) including the table which means it just about makes it small enough for this section.
There is no error checking and it is up to the calling routine to ensure that the source byte will become a valid BCD byte or word.
Last page update: 28th August, 2003. | e-mail me |