Decimal to Binary Conversion
Posted: Wed Mar 03, 2004 12:56 pm
After reading the thread on binary to decimal I tried implementing the reverse algorithm trying to avoid lookup tables and/or multiply by 10 routines. This is what I came up with.
Code: Select all
; Extracts a 16 bit binary number from a 24 bit BCD value.
;
; If the BCD value was bigger than 65535 then some bits will be left in
; BCD area at the end of of the conversion.
BCD2BIN LDX #16 ;Set the bit count
.OUTER LDY #2 ;Set BCD byte count
CLC ;Ensure that C=0 on first shift
.INNER LDA BCDW,Y ;Divide the BCD byte by two
ROR
PHP ;Save the bit that was shifted out
.IF __65C02__
BIT #$80 ;Does the hi nybble need correction?
BEQ *+5
SEC
SBC #$30
BIT #$08 ;Does the lo nybble need correction?
BEQ *+5
SEC
SBC #$03
.ELSE
BIT BIT7 ;Does the hi nybble need correction?
BEQ *+5
SEC
SBC #$30
BIT BIT3 ;Does the lo nybble need correction?
BEQ *+5
SEC
SBC #$03
.ENDIF
PLP ;Finally recover the carry
STA BCDW,Y
DEY ;Repeat for next BCD byte
BPL .INNER
ROR BINW+1 ;Catch the remainder
ROR BINW+0
DEX ;And repeat
BNE .OUTER
BRK
; 6502 does not support BIT with immediate data so we must deposit
; these constants.
.IF __6502__
BIT7 .DB $80
BIT3 .DB $08
.ENDIF