Inspired by the interesting discussions about fast binary to decimal/BCD conversions, I thought about how such a conversion could be expressed with a simple formula.

Here it is for packed BCD encoding in C language (I would assume it is state of the art):

unsigned long bin2bcd (uint32_t n) // convert 16 bit binary n to 5 digit BCD (packed) { n = n + 6 * (n/10 + 16*(n/100) + 256*(n/1000) + 4096*(n/10000)); return n; }

Using GCC this function runs on an ATmega328P in typically 158 µsec @16 MHz.

This is a timing envelope for converting all numbers 0 to 2^16-1:

The screenshot was taken using this program, which also lists the decimal and BCD numbers on an attached terminal:

for (i = 0; i <= 65535; i++) { LED_ON; m = bin2bcd(i); LED_OFF; printf ("%5lu : %05lX\n", i, m); }

As expected, the given function runs much slower with GCC than with the discussed routines written in AVR assembly language.

I would be interesting to know how fast this formula is executed when using FPGAs.

Of course you can check the formula with Excel as well.

For example if you got a decimal number in cell A2, the 5-digit BCD number can be represented in cell B2 as follows:

=DEC2HEX(A2+6*(INT(A2/10)+16*INT(A2/100)+256*INT(A2/1000)+4096*INT(A2/10000));5)

Enjoy!