Test Your EQ (Engineering Quotient)

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[3] = {0, 0, 0};
  int i;

  for (i=0; i<16; ++i) {
    adjust (&bcd[0]);
    adjust (&bcd[1]);
    adjust (&bcd[2]);

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

  return (unsigned long) (bcd[2]<<16) | (bcd[1]<<8) | bcd[0];
}

— ADVERTISMENT—

Advertise Here

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	...

Keep up-to-date with our FREE Weekly Newsletter!

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


Note: We’ve made the Dec 2022 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.

— ADVERTISMENT—

Advertise Here

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.

Supporting Companies

Upcoming Events


Copyright © KCK Media Corp.
All Rights Reserved

Copyright © 2023 KCK Media Corp.

EQ #8

by Circuit Cellar Staff time to read: 1 min