## Hex to BCD format . . HELP

4 posts / 0 new
Author
Message

I am trying to send info to set a RTC.

I understand I need to convert the received data, which is in hex format to BCD format to put into the RTC registers. Things are OK up to integer 15 (because everything is in the low nibble?), but when I try to convert integer 16 I get 10. It appears to me that everytime you get a "carry" into the high nibble you will have to do something "tricky" with the low nibble. Tricky = lookup table or recursive algorithm??

I have searched for hex to bcd conversion programs, but they seem to be way over the top for just changing an integer of max value 59 to BCD format.

Changing from BCD format to hex was easy to do, but I just can't work out how to do it the other way :(

Thanks for any "pointers".
davef

The subtract-and-count method is the brute force approach, but it has the advantage of being obvious. You take a table of values: 10000, 1000, 100, 10 depending on how big of a number you need to code. Then you start at the top and subtract the table number from the value while counting the number of subtracts. Then the value is less than the table number, move to the next table number and repeat. Do that until the value is less than 10.

Tim Ressel
Portland, OR
timr@earthling.net

/*
convert from binary value into bcd
*/
unsigned char bcd_con(unsigned char value)
{
unsigned char data;
for(data=0; value>9;)
{
value-=10;
data+=0x10;
}
data+=value;
return data;
}

Yes I am getting grumpy!