# BCD2Binary converter and Binary to BCD converter

Discussion in 'Embedded Systems and Microcontrollers' started by Dumken, Jun 16, 2015.

1. ### Dumken Thread Starter New Member

Oct 7, 2014
29
0
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

File size:
308.5 KB
Views:
0
2. ### tshuck Well-Known Member

Oct 18, 2012
3,527
675
It's a pretty standard approach, did you do a search for binary to BCD code explanation?

Dumken likes this.
3. ### Dumken Thread Starter New Member

Oct 7, 2014
29
0
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.

4. ### Dumken Thread Starter New Member

Oct 7, 2014
29
0
pls can you give me a value i can assume as "a"

5. ### djsfantasi AAC Fanatic!

Apr 11, 2010
3,496
1,253
"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)

Dumken likes this.
6. ### ErnieM AAC Fanatic!

Apr 24, 2011
7,907
1,789
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.

7. ### Dumken Thread Starter New Member

Oct 7, 2014
29
0
Thank you guys i now understand