I have time values that are retrieved and stored as decimal values. But the same value needs to be written as BCD to the registers of an external RTC.
For example
uint8_t year = 19; //year is 2019, value in decimal
spi_rtcc_wr(rtcc reg: RTCYEAR, time_var: 0x19); //but external RTC needs that 19 to be in BCD (0x19) to represent 2019
How can I convert the decimal 19 to a BCD value of 0x19?
If I insert year as the time_var it accepts it but stores the value as BCD 13.
Need decimal integer to be BCD
-
- Posts: 32
- Joined: Tue Feb 05, 2019 5:26 pm
Re: Need decimal integer to be BCD
If it can help anyone, I used some code from internet, modified it so that you can use a variable to convert.
Code: Select all
// C program to convert hexadecimal to decimal
#include <math.h>
#include <stdio.h>
#include <string.h>
int decimalNumber = 0;
uint8_t hexa1;
uint8_t year;
void hextodec (void);
void app_main(void)
{
year = 19;
hexa1=year;
hextodec();
year = decimalNumber;
// printing the result
printf("Decimal Number : %d", year);
}
void hextodec(void)
{
decimalNumber = 0;
char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char hexadecimalnumber[4];
sprintf(hexadecimalnumber, "%d", hexa1);
int i, j, power = 0;
// Converting hexadecimal number to equivalent decimal
// number
for (i = strlen(hexadecimalnumber) - 1; i >= 0; i--) {
// search if given input character is present in the
// array or not. if it present in the array then
// find the equivalent decimal number for each hexa
// digit
for (j = 0; j < 16; j++) {
if (hexadecimalnumber[i] == hexDigits[j]) {
decimalNumber += j * pow(16, power);
}
}
power++;
}
}
-
- Posts: 1821
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Re: Need decimal integer to be BCD
For future readers, a less creative way to do it is
and the inverse operation
Code: Select all
uint8_t bcd = (16 * (intValue / 10)) + (intValue % 10);
Code: Select all
uint8_t intValue = (10 * (bcd / 16)) + (bcd % 16);
Who is online
Users browsing this forum: No registered users and 43 guests