Talk:Converting Binary Coded Decimal

From BeebWiki
Jump to: navigation, search

More efficient variants?

The given routines (counting up/down by 1) seem a whole waste of cpu cycles to me ...
My would suggest as replacement (or at least as additional variants):
(Alas, these variants needs an extra memory location.)

\ Convert binary number to BCD
\ ----------------------------
\ On entry, A=value 0-99
\ On exit,  A=BCD value &00-&99
\           X, Y, tmp corrupted
.BINtoBCD
SED             :\ decimal mode
LDY #0          :\ init. bcd value
ASL:ORA #1      :\ end marker
.loop
TAX             :\ save binary value
TYA             :\ fetch bcd value
STA tmp         :\ store as 2nd parameter
ADC tmp         :\ 2*tmp + carry
TAY             :\ save bcd value
TXA             :\ fetch binary value
ASL             :\ binary 2*
BNE loop        :\ 8 times, until end marker shifted out
TYA
CLD:RTS         :\ leave with decimal mode off


\ Convert BCD to Binary
\ --------------------------------------------
\ On entry, A=BCD value &00-&99
\ On exit,  A=binary value 0-99
\           X, tmp corrupted
.BCDtoBIN
TAX             :\ save low bcd digit
LSR             :\ high digit
LSR
LSR
LSR             :\ / 16 -> 0-9
STA tmp
ASL             :\ -> *2
ASL             :\ -> *4
ADC tmp         :\ -> *5
ASL             :\ -> *10
STA tmp
TXA             :\ low digit
AND #&0F        :\ high digit masked out
ADC tmp         :\ final binary value
RTS

-JeeK (talk) 19:28, 6 October 2016 (UTC)