# [PIC]0 to 999 BCD to Binary conversion

Status
Not open for further replies.

#### rparthiban69

##### Full Member level 4
Hi

I need to convert (0 to 999) BCD to Binary Conversion - EEPROM data storing purpose.

I need also Binary to BCD conversion.

I am using Hitech c compiler.

Thanks.

#### doraemon

##### Super Moderator
Staff member
Hello!

Why don't you start telling us what you already did?

Dora.

#### rparthiban69

##### Full Member level 4
This for 0-99

Code:
unsigned int  bin2bcd(unsigned int binary_value)
{
unsigned int temp;
char retval;

temp = binary_value;
retval = 0;

while(1)
{
// Get the tens digit by doing multiple subtraction
// of 10 from the binary value.
if(temp >= 10)
{
temp -= 10;
retval += 0x10;
}
else // Get the ones digit by adding the remainder.
{
retval += temp;
break;
}
}

return(retval);
}

// Input range - 00 to 99.
unsigned char bcd2bin(unsigned char bcd_value)
{
char temp;

temp = bcd_value;
// Shifting upper digit right by 1 is same as multiplying by 8.
temp >>= 1;
// Isolate the bits for the upper digit.
temp &= 0x78;

// Now return: (Tens * 8) + (Tens * 2) + Ones

return(temp + (temp >> 2) + (bcd_value & 0x0f));
}

#### doraemon

##### Super Moderator
Staff member
Hello!

So you're interested only in positive numbers, right?

Why do you perform a division by hand?
You have a number of 2 digits. For example 69.
If you do 69/10, you get 6
If you do 69%10, you get 9.
Then why not saying that retval is 16 * the number of tens and then add the number of units?

By the way, what will happen if you enter more than 100 in your function? You are talking about
tens but not hundreds and thousands.

Then for the bcd2bin, if you start with 0x69, then it's basically the same:
0x69 / 16 = 6
0x69 % 16 = 9. Then return 6*10 + 9.

By the way you don't need parentheses for return. return retval; is fine.

Dora.

rparthiban69

### rparthiban69

Points: 2

#### rparthiban69

##### Full Member level 4
Could please explain with code level,
I need to convert Decimal value 0 to 999 only.

Please send the conversion BCD to Binary and Binary to BCD.

If any Dec to BCD conversion available or not?

#### zuisti

Code:
//binary_value: 0-999
unsigned int  bin2bcd(unsigned int binary_value)
{
unsigned int temp = 0;

while (binary_value > 99)
{
binary_value -= 100;
temp += 0x100;
}

while (binary_value > 9)
{
binary_value -= 10;
temp += 0x10;
}

return (temp + binary_value);
}

//bcd_value: 0-0x999
unsigned int  bcd2bin(unsigned int bcd_value)
{
unsigned int temp = 0;

while (bcd_value > 0x99)
{
bcd_value -= 0x100;
temp += 100;
}

while (bcd_value > 9)
{
bcd_value -= 0x10;
temp += 10;
}

return (temp + bcd_value);
}

rparthiban69

Points: 2