LONGJA
Posts: 23
Joined: Wed Mar 28, 2018 4:04 pm

Using Hex value in a Calculation

Tue Jun 12, 2018 10:27 am

Hi there,

I'm trying to build a program that calculates the difference, in seconds, between two times. I want to read the time from an I2C realtime clock and convert the time into a total in seconds. For example, for 11:18:58, I want to be able to do (11x3600) + (18x60) + (58) = 40738. However the reading I get back from the realtime clock are hex values and when I try to convert them to a decimal the values change accordingly, for example 11 changes to 17. This then messes up the calculations. Please see below:

int total
int sum

Readtime();

printf("%02x:%02x:%02x", buf[2], buf[1], buf[0]);

total = (buf[2])*3600;

printf("total = %d", total);

I've seen various bits of code for converting from a hex to a decimal but nothing that will allow me to use the raw hex value. Any suggestions greatly appreciated, thanks.

James

User avatar
buja
Posts: 558
Joined: Wed Dec 31, 2014 8:21 am
Location: Netherlands

Re: Using Hex value in a Calculation

Tue Jun 12, 2018 11:08 am

If you already have a number as an integer (int), there is no need to convert between decimal and hexadecimal.
The only thing you have to do is decide in which format you want to print the number:

int a = 0x10;
printf("%02x", a); => this prints 10
printf("%02d", a); => this prints 16

The numerical value of a does not change, only the printed output.
Last edited by buja on Tue Jun 12, 2018 12:49 pm, edited 1 time in total.

hippy
Posts: 7127
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Using Hex value in a Calculation

Tue Jun 12, 2018 11:28 am

buja wrote:
Tue Jun 12, 2018 11:08 am
If you already have a number as an integer (int), there is no need to convert between decimal and hexadecimal.
Correct but values from an RTC are usually BCD encoded bytes rather than hex. For example 0x19 BCD represents 19 decimal.

decimal = bcd - ( ( bcd >> 4 ) * 6 );

hippy
Posts: 7127
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Using Hex value in a Calculation

Tue Jun 12, 2018 11:47 am

Untested -

Code: Select all

#define BcdToBin(bcd) ( bcd - ( ( bcd >> 4 ) * 6 ) ) 

Readtime();

printf("%02x:%02x:%02x", buf[2], buf[1], buf[0]);

total = BcdToBin(buf[2]) * 3600
      + BcdToBin(buf[1]) * 60
      + BcdToBin(buf[0]);

printf("total = %d", total);

Return to “C/C++”