Page 1 of 1

Need decimal integer to be BCD

Posted: Mon Dec 09, 2024 12:58 am
by commando_j
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.

Re: Need decimal integer to be BCD

Posted: Mon Dec 09, 2024 5:30 am
by commando_j
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++; 
    } 
}   

Re: Need decimal integer to be BCD

Posted: Tue Dec 10, 2024 2:04 pm
by MicroController
For future readers, a less creative way to do it is

Code: Select all

uint8_t bcd = (16 * (intValue / 10)) + (intValue % 10);
and the inverse operation

Code: Select all

uint8_t intValue = (10 * (bcd / 16)) + (bcd % 16);