Electrical – How to we multiply two 2-digit BCD numbers

7segmentdisplayassemblycodepic

I am designing a PIC18F4520 microcontroller based system. By using this system I want to multiply two numbers. Each number is a 2-digit BCD number. Such as 73*27 and I want to see results as 2715 at a 4 digit seven segment display. I have a problem creating algorithms while multiplying those numbers. How can we multiply those numbers?

Best Answer

The obvious answer is most certainly the most viable here

  1. Convert BCD digits to binary numbers, multiply the upper digit with 10, add them.
  2. Do that to both BCD numbers. You get both BCD numbers represented as binary, the way computers actually deal with them.
  3. Multiply them.
  4. Convert the result back to BCD.

This is a pretty dated microcontroller, but it can multiply (binary) numbers.

There's really no reason to do anything but the obvious, trivial.

I'll be honest: that schools and universities still teach BCD is an anachronism. There's no practical reason. Conversion to BCD is such a marginal problem that there'd be so many better topics to teach in a basics of digital logic class... it always makes me a bit sad.


As @jonk correctly points out, you can do "hand multiplication", of course, with your digits, should you feel the desire to do this in decimal!

But it would teach you something that is not clever: doing decimal computation on a binary computer.


An incredibly easy way of converting a two-digit BCD to binary is putting the two 4-bit digits into one 8-bit Byte (higher_bcd_digit<<4 | lower_bcd_digit) and using that as index into a 256-entry-table containing the binary representation of the number. That is how I would implement the BCD-to-binary conversion.
I think (not sure) on PIC18 that would result in a single-cycle 2-digit-BCD-to-binary conversion: Impossible to beat.


Sure, 156 of your 256 possible entries would be entries you don't care about. But you've got 32 kB of program memory, so that's not really a bottleneck.

It gets worse: because there's so much free space in that table, you can fill the larger "don't care" table "gaps" with your program code to save space. Just needs a bit of manual positioning of code, something you do anyway, according to your "" tag.

So, there you go, maybe four cycles (i.e. about 0.4 µs) to convert your two BCD numbers to binary. A multiplication, and a conversion back to BCD.

That conversion would take longer (can't do the trick you can do for an 8 bit table on the harvard architecture of the PIC18, so can't simply store all possible products in a table in program memory), but again, the conversion is so simple on CPUs like this one, since they support multiplication and subtraction out of the box.