# BCD to binary conversion algorithm

Discussion in 'Embedded Systems and Microcontrollers' started by Eric007, Aug 6, 2011.

1. ### Eric007 Thread Starter Senior Member

Aug 5, 2011
1,054
33
Hi all,

Attached is 2 versions of code that convert 2 digit BCD to 8 bit binary...

I'm trying to understand the algorithm behind these codes...
I just need to understand oNe of them...
Can anyone explain in details the algorithm of one of them in a big paragraph??
Also I wana know how is the input represented in the code
Regards,

File size:
23.5 KB
Views:
344
2. ### Markd77 Senior Member

Sep 7, 2009
2,803
594
All it's doing is (10 X the left 4 bits)+(the right 4 bits). They have just been optimised compared to what someone might write as a first attempt.

3. ### THE_RB AAC Fanatic!

Feb 11, 2008
5,435
1,305
You can do it with a very small amount of code as successive subtraction, like this;

Code ( (Unknown Language)):
1.
2. // converts two 4bit BCD numbers to 2 decimal digits, orig BCD is
3. // in numb, and numb is destroyed during the conversion
4. digit1 = 0;
5. while(1)
6.   if(numb & 0xF0)
7.   {
8.     digit1++;
9.     numb -= 16;
10.   }
11.   else break;
12. }
13. digit0 = numb;
14.

4. ### Eric007 Thread Starter Senior Member

Aug 5, 2011
1,054
33
thx The RB but i needed it in assembly language...

5. ### atferrari AAC Fanatic!

Jan 6, 2004
2,663
783
To understand it, you could work it by hand, following what the assembler does.

I used to do it in graph paper where every square was a bit from a register.

After some time I managed to write my own division routine which I still use today. (16F family at that time, now ported to the 18F family - PIC micros)

It is all here

http://cablemodem.fibertel.com.ar/atferrari/

under PICs

6. ### atferrari AAC Fanatic!

Jan 6, 2004
2,663
783
Oh, maybe your doubts are much more basic:

Do you know what "packed" does mean?

Binary coded decimal is well explained in Wikipedia. Once you understand it, going step by step through the code should be not difficult.

7. ### THE_RB AAC Fanatic!

Feb 11, 2008
5,435
1,305
That's why I typed it in the simplest crudest possible form, so it would be effortless to convert to ASM or BASIC etc.

If you are confused by the C code's peculiarities, here is a more "standard math" way of typing it;

Code ( (Unknown Language)):
1.
2. // converts two 4bit BCD numbers to 2 decimal digits, orig BCD is
3. // in numb, and numb is destroyed during the conversion
4. digit1 = 0;
5. while(numb >= 16)   // loop WHILE numb is greater or equal to 16
6. {
7.     digit1 = (digit1 + 1);    // add 1 to digit1
8.     numb = (numb - 16);   // subtract 16 from numb
9. }
10. digit0 = numb;
11.

8. ### atferrari AAC Fanatic!

Jan 6, 2004
2,663
783
What you posted is assembler already!