BCD to binary conversion algorithm

Thread Starter

Eric007

Joined Aug 5, 2011
1,158
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,
 

Attachments

Markd77

Joined Sep 7, 2009
2,806
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.
 

THE_RB

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

Rich (BB code):
// converts two 4bit BCD numbers to 2 decimal digits, orig BCD is
// in numb, and numb is destroyed during the conversion
digit1 = 0;
while(1)
  if(numb & 0xF0)  
  {
    digit1++;
    numb -= 16;
  }
  else break;
}
digit0 = numb;
 

atferrari

Joined Jan 6, 2004
4,770
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
 

atferrari

Joined Jan 6, 2004
4,770
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.
 

THE_RB

Joined Feb 11, 2008
5,438
thx The RB but i needed it in assembly language...
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;

Rich (BB code):
// converts two 4bit BCD numbers to 2 decimal digits, orig BCD is
// in numb, and numb is destroyed during the conversion
digit1 = 0;
while(numb >= 16)   // loop WHILE numb is greater or equal to 16
{
    digit1 = (digit1 + 1);    // add 1 to digit1
    numb = (numb - 16);   // subtract 16 from numb
}
digit0 = numb;
 
Top