Continue to Site

# [SOLVED]How can i convert Decimal to Dual-BCD.

Status
Not open for further replies.

#### Micro Lover

##### Member level 2
hi

i m using Keil, and C language
the problem is that, i have one decimal number, like 27, that will be 11011 in binary, but if i split the 27 then it will be "2" and "7" , in binary, "10" and "111", i want to convert it to "00100111", the first four bits(right site) for 7 and other 4 for 2.

how can i convert it?

If you can split the 27 to 2 and 7 then you can simply do

bcd= (0b10<<4) | 0b0111

Alex

Micro Lover

### Micro Lover

Points: 2
very sorry Alex, i cant understand, i have a value 2 and 7, (splited) but how can i Out it to the port

Data -> 0 0 1 0 0 1 1 1
pin 7-> | | | | | | | | Pin 0
======== Port Pins ==============

I don't know the port name of your mcu but suppose it is PORTA like in AVR

PORTA=(0x2<<4) | 0x7;

0x2 is 0b00000010
0x2<<4 shifted four times to the left so the result is 0b00100000
then 0b00100000 | 0b00000111 gives 0b00100111

Alex

Last edited:
Micro Lover

### Micro Lover

Points: 2
now it working Perfectly

thanks

The principle of the conversion from binary to BCD (Binary Coded Decimal) you can grasp from my commented example (in C) shown below:
it's conversion of a binary unsigned integer (in the example the binary value must be less than 10000!) to the corresponding 'condensed' BCD.

/*----------------------------------------------------------------------------*/
/* Conversion of "unsigned int" (BIN) to condensed BCD, range 0 to 9999 only! */
/*----------------------------------------------------------------------------*/

unsigned int Bin2BCD(unsigned int bin) // bin < 10000!
{
 unsigned int bcd; unsigned char aux; aux = bin / 1000; bin -= aux * 1000; bcd = aux << 4; aux = bin / 100; bin -= aux * 100; bcd |= aux; bcd <<= 8; aux = bin / 10; bin -= aux * 10; aux = (aux << 4) | bin; bcd |= aux; return(bcd); ​ // condensed BCD word (in the end it contains the result) // auxiliary variable // number of 'thousands' // remainder = input value "without 'thousands'" // shifts 'thousands' in the upper nibble of lower byte // number of 'hundreds' // remainder = input value "without 'thousands' + 'hundreds'" // 'hundreds' "joined" with 'thousands' (lower nibble of lower byte) // shifts 'thousands' and 'hundreds' in the upper byte // number of 'tens' // remainder = 'units' // 'tens' in the upper nibble, 'units' in the lower one // 'thousands', 'hundreds', 'tens' and 'units' joined together // output of the result

}
/*----------------------------------------------------------------------------*/

For 1 byte (unsigned char) the solution is appropriately easier, of course.

Eric

Status
Not open for further replies.