# EQ #8  The C code below converts an unsigned 16-bit binary number into its decimal equivalent, in packed BCD format. Does this algorithm extend to other sizes of binary numbers?

``````void adjust (unsigned char *p)
{
unsigned char t = *p + 3;
if (t & 0x08) *p = t;
t = *p + 0x30;
if (t & 0x80) *p = t;
}

unsigned long binary2bcd (unsigned int n)
{
unsigned char bcd = {0, 0, 0};
int i;

for (i=0; i<16; ++i) {

bcd <<= 1;
if (bcd & 0x80) ++bcd;
bcd <<= 1;
if (bcd & 0x80) ++bcd;
bcd <<= 1;
if (n & 0x8000) ++bcd;
n <<= 1;
}

return (unsigned long) (bcd<<16) | (bcd<<8) | bcd;
}``````

Yes, this algorithm generalizes easily. You just need to specify the correct number of bytes to hold the BCD result for the size of binary number that you’re converting:

``````Binary bytes:	 1	2	3	4	5	...
Loop iterations: 8	16	24	32	40	...
Decimal digits:	 3	5	8	10	13	...
BCD bytes:	 2	3	4	5	7	...``````

Don't miss out on upcoming issues of Circuit Cellar. Subscribe today!

Note: We’ve made the October 2017 issue of Circuit Cellar available as a free sample issue. In it, you’ll find a rich variety of the kinds of articles and information that exemplify a typical issue of the current magazine.

Would you like to write for Circuit Cellar? We are always accepting articles/posts from the technical community. Get in touch with us and let's discuss your ideas.