Wednesday, January 21, 2009

2-digit BCD to decimal conversion

Now, I'm working on the full feature clock using DS1307. In the clock, I use many BCD to decimal (bcd2dec) and decimal to BCD conversions for reading and setting time of the DS1307 RTC. MikroC provides buit-in functions for these conversions but the functions consume modest amount of MCU memory space. I have came up with simple functions that consume less memory for doing 2-digit BCD to decimal and the reverse conversions.

2-digit BCD to Decimal conversion function:
unsigned short myBcd2Dec(unsigned short bcd){
return ((bcd >> 4)*10+(bcd & 0x0F));
}

Example: myBcd2Dec(01000101) = 45

2-digit Decimal to BCD conversion function:
unsigned short myDec2Bcd(unsigned short dec){
return (((dec/10)<<4)(dec%10));
}

Example: myDec2Bcd(45) = 01000101

3 comments:

Unknown said...

in the code there is not mentionaned any date and time is it?

punkky said...

No, the code is not the full clock code. It's just the code for 2-Digit BCD to decimal conversion and vise versa. The code for the full working Clock will be posted later as I am working on it.

Stuart said...

Useful code, it helped me check my own version of bcd conversion. But I think there is a typo (missing +) in the dec to bcd version: you shift the tens value right but should then add in the units (mod) value - not multiply.