1

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);
gusdleon
  • 115
  • 1
  • 6
  • 1
    Computers don't work with hex of decimal values; they all work in binary. Hex and decimal are two ways to display numbers to humans, in a more compact way. You should know how hex works: `0x133015` is `0x13 * 0x1000 + 0x30 * 0x100 + 0x15 * 0x1`. By the same logic, decimal `133015` is `13 * 10000 + 30 * 100 + 15`. I don't see the relation between `0x133015` and `133015` though. `0x13` is 19 hours, `0x30` is 48 minutes, and `0x15` is 21 seconds. – MSalters Dec 17 '20 at 02:40

1 Answers1

2

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

user3386109
  • 34,287
  • 7
  • 49
  • 68