Notes from Scott Dattalo on converting a Byte to BCD quickly:
QUICK TRICK ONE:
The routine I have implemented for the PIC uC is based on binary comparisons. It takes advantage of this little trick to quickly ascertain the ones' digit:
If you look at the ones' digit for 2^N you see this pattern:
If it wasn't for the annoying 6's, you could simply sum the nibbles and get the ones' digit after a relatively simple binary to BCD conversion.
For example, the ones' digit for 2^5 = 0x20 is 2 (because 0x20 = 32 decimal).
This sum-of-digits trick works even if the binary number is not a perfect power of 2.
For example, consider $EF:
CODE
0xEF = 239 base 10, the one's digit is '9'
$E + $F = 0x1D
A binary to BCD conversion of 0x1D yields 0x29 (because 1d hex is 29 decimal). And the one's digit is '9', just like the one's digit of 0xEF.
Now, this trick only works if bit 4 is not set. (notice my contrived exampled has every bit set except for that one). It's simple enough to test if bit 4, (and bit 8 for 16-bit conversions) and to subtract 1 and then add 6 (or simply add 5) if it is.
SECOND OBSERVATION:
The second observation is that the sum of all of the tens' digits of 2^n (for n<8) is less than 16, and thus can fit into one nibble. This simplifies having to deal with overflow until after all of the digits have been added together.
What I'm saying is simply that if you look at the eight 2^n numbers 1,2,4,8,0x10,0x20,0x40,0x80 and sum all of the upper nibbles together: 0x10 + 0x20 + 0x40 + 0x80 you get 0xF0 which doesn't cause a carry.
THIRD OBSERVATION:
The third observation is that the BCD result is greater than 200 only if the most significant bit is set.
Note: that this is necessary but not sufficient condition. e.g. 0x80 has the MSB set, but is only 128, but 200 is 0xC8.
Forumer™ is Voted #1 Free Forum Hosting provider
Build your own community today with the largest message board hosting company.