BCD2Binary converter and Binary to BCD converter

Thread Starter

Dumken

Joined Oct 7, 2014
31
Hi good day guys.. Pls can someone help explain this conversion for me?

int Binary2BCD(int a)
{
int t1, t2;
t1 = a%10;
t1 = t1 & 0x0F;
a = a/10;
t2 = a%10;
t2 = 0x0F & t2;
t2 = t2 << 4;
t2 = 0xF0 & t2;
t1 = t1 | t2;
return t1;
}

int BCD2Binary(int a)
{
int r,t;
t = a & 0x0F;
r = t;
a = 0xF0 & a;
t = a >> 4;
t = 0x0F & t;
r = t*10 + r;
return r;
}


The main code is down here
 

Attachments

tshuck

Joined Oct 18, 2012
3,534
int Binary2BCD(int a)
{
int t1, t2;
t1 = a%10; // get the units multiplier
t1 = t1 & 0x0F; // make sure it's only the least significant 4 bits
a = a/10; // get the next digit place (10s place)
t2 = a%10; get the tens multiplier (shifted over from the divide)
t2 = 0x0F & t2;// make sure it's only the least significant 4 bits
t2 = t2 << 4;//shift the tens multiplier to the upper 4 bits (nibble)
t2 = 0xF0 & t2;//unnecessary provided it appends 0 on a shift operation.
t1 = t1 | t2; // combine the two nibbles. t2 is the higher nibble (...xxxx0000) and t1 is the lower nibble (...0000xxxx)
return t1; //return the BCD number
}

int BCD2Binary(int a) //do the opposite of Binary2BCD()
{
int r,t;
t = a & 0x0F;
r = t;
a = 0xF0 & a;
t = a >> 4;
t = 0x0F & t;
r = t*10 + r;
return r;
}
It's a pretty standard approach, did you do a search for binary to BCD code explanation?
 

Thread Starter

Dumken

Joined Oct 7, 2014
31
yes i did but i got other methods not similar to this. i just want to understand this method. Thanks for the explanation let me study it.
 

djsfantasi

Joined Apr 11, 2010
9,160
"a" is your input value. Whatever binary value you want to convert to BCD. So pick a value. How about 00111000b? That's 56 decimal. Then, the function Binary2BCD would return 01010110b. Or 00001100b. The function returns 00010010b. (12 decimal)
 

ErnieM

Joined Apr 24, 2011
8,377
Do you know what a "BCD" value is? Is it simple a number between 0 and 9 that fits into 4 bits. It is also used here to pack 2 such digits into one 8 bit quantity, so the may value passed into BCD2Binary() would be 153 decimal, or 0x99 in hex.

"a" is what is passed into the function to convert. For Binary2BCD() the value had best be limited to 0x63 hex or 99 decimal or the result will be nonsense.

Neither function does any error checking so the calling function must insure the values are within the proper range. There is also an issue with the sign, a proper function would use unsigned characters (positive values limited to 8 bits) instead of a (signed by default) int integer of variable length (depends on compiler specifics).

Also there is much tightning up of this code to be done. It does repeat some calculations and sperad things over many steps that could be combined.

Do look up the opperators % & | << >> in addition to the standard / and * ops.
 
Top