Hi, Does anyone know how to convert a BINARY 8 bit to a 2 digit packed BCD. Example if I have value 0x0C (wich is 12 decimal) the result will be 12 or a char value of 0x12. thank you, Adi,
This wouldn't be homework would it? Firstly, an 8-bit value will be in the range 0 to 255, so obviously some values require more than 2 decimal digits. To convert a value in the range 0..99, simply divide the value by 10 to obtain the most significant digit and take the modulo 10 value to obtain the least significant digit. The DIV instruction will all this in one go. Compacting two digits into one byte requires moving some bits and ORing the results together. To convert a decimal digit to ASCII, you just have to add a magic value.
Hi, Thanks for the HELP. No its not homework...I finished school long time ago :-) It was for communicating with a DALLAS RTC DS1337. Is your code better than this one ? I mean will it run faster ? Because I didn't use the MODULO 10, here is what I did: char bin2BCD8(char cValue) { char cDig10=0; char cDig1=0; char cTemp; cTemp=cValue; // Backup the value do{ cTemp=cTemp-10; if(cTemp<0) { break; } else { cDig10++; } }while(1); cDig1=cValue-(cDig10*10); cDig10=(cDig10<<4)|cDig1; return cDig10; }
Hi
unsigned char chartobcd(unsigned char n) { return ((n / 10) << 4) | (n % 10); }
the above should be
unsigned char chartobcd(unsigned char ) { if (n >99) crash(); return ((n / 10) << 4) | (n % 10); }
Hi, WOW I'm learning from the PRO...your code seems very compact. I will try it. But will I get a packed BCD value ? I'll get back to you if I have some problems. Thank you, Adi,
Hi If a want to write a BCD number to a RTC, I prefear to do that check in the input routine, and that because of the different of input values. year = 00 - 99 month = 01 - 12 day = 01 - 31 hour = 0 - 23 min = 0 - 59 sec = 0 - 59 Ingvar
will I get a packed BCD value ? Yes, by "ORing" the two halves of the number together, you get a single byte, two digit BCD number.
View all questions in Keil forum