Transfer hex value to a decimal value

I'm trying to manipulate the values of a struct atime1 with values .Hours, .Minutes, .Seconds, and for some reason, the values I need are the HEX values of these variables, all tree are int.

Then I "concatenate" the three variables in a way the hex values are not altered. HEX values:

aTime.Hours=0x13
aTime.Minutes=0x30
aTime.Seconds=0x15
ttt=0x133015

Then I need to convert that variable ttt with dec values of 1257493 and 0x133015 to a decimal value of 133015.

That's where I dont know how to make that conversion.

Here my code so far.

HAL_RTC_GetTime(&hrtc, &aTime1, RTC_FORMAT_BCD);
HAL_RTC_GetDate(&hrtc, &aDate1, RTC_FORMAT_BCD);
ttt = aTime1.Hours;
ttt = ((ttt % 100000) * 256 + aTime1.Minutes);
ttt = ((ttt % 100000) * 256 + aTime1.Seconds);
1

1 Answer

The information from the real time clock (RTC) is coming to you in binary-coded decimal (BCD) format. That means that each byte consists of two decimal digits. The most-significant decimal digit (MSDD) is in the upper four bits, and the least-significant decimal digit (LSDD) is in the lower four bits.

So the first step is to extract individual digits, and I would store those digits in an array. To extract the MSDD, shift right by 4 bits. To extract the LSDD, mask with 0xf.

After extracting the digits, a for loop can be used to produce the final result.

The code looks like this:

#include <stdio.h>
struct stTime
{ int Hours; int Minutes; int Seconds;
};
int main(void)
{ struct stTime aTime = { 0x13, 0x30, 0x15 }; int digits[6]; digits[0] = aTime.Hours >> 4; digits[1] = aTime.Hours & 0xf; digits[2] = aTime.Minutes >> 4; digits[3] = aTime.Minutes & 0xf; digits[4] = aTime.Seconds >> 4; digits[5] = aTime.Seconds & 0xf; int result = 0; for (int i = 0; i < 6; i++) result = result * 10 + digits[i]; printf("%d\n", result);
}

Ouput: 133015

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like