Converting Binary Coded Decimal

From BeebWiki
Revision as of 01:20, 3 October 2016 by Jgharston (talk | contribs)
Jump to: navigation, search

Binary Coded Decimal (BCD) is a method of representing a decimal number as a hexadecimal value using the hex digits 0-9 and ignoring A-F. For example, the number 21 (hex &15) would be represented as &21 (decimal 33). It can be a convenient internal representation of decimal numbers as each hexadecimal digit can be displayed without any further processing. See Wikipedia. BCD values can be decoded with:

   number% = VALSTR$~bcd%

Numbers can be encoded in BCD using:

   bcd% = EVAL("&"+STR$number%)

A 7-bit binary number can be converted to BCD so it can be printed in hex with the following 6502 code:

   \ Convert binary number to BCD
   \ ----------------------------
   \ On entry, A=value 0-99
   \ On exit,  A=BCD value
   \           X corrupted
   .BINtoBCD
   TAX             :\ Transfer number to X
   LDA #&99        :\ Start with -1 in BCD form
   SED             :\ Switch to Decimal arithmetic
   .PrDecLp
   CLC:ADC #1      :\ Add 1 with BCD arithmetic
   DEX:BPL PrDecLp :\ Add 1 for the total in X until X<0
   CLD:RTS         :\ Switch back to Binary arithmetic


Jgharston 21:11, 23 June 2007 (BST) Jgharston (talk) 00:19, 3 October 2016 (UTC)