Weird Math Error

G'day all,

I'm trying to get the current time from an RTC (ie 21:15:33) and return it as a long (ie 211533).

I thought some very simple maths should achieve this, but alas, I'm stumped by the output. The value of 'lNewHour' should be 210000 (21 * 10000), yet it's coming back as 13392. The minute calculation seems to be working correctly (15*100=15000).

This is just dumb multiplication, so I must have missed something, but I just can't see what.

Any and all assistance is greatly appreciated.

Cheers....

unsigned long getClockTimeAsLong()
{
  DateTime daDate = RTC.now();
  int lHour=daDate.hour();
  int lMinute=daDate.minute();
  int lSecond=daDate.second();
  
  Serial.print("lHour=");
  Serial.println(lHour);
  
  Serial.print("lMinute=");
  Serial.println(lMinute);

  Serial.print("lSecond=");
  Serial.println(lSecond);

  long lNewHour=lHour*10000;
  long lNewMinute=lMinute*100;
  
  Serial.print("lNewHour=");
  Serial.println(lNewHour);
  
  Serial.print("lNewMinute=");
  Serial.println(lNewMinute);

  Serial.print("lSecond=");
  Serial.println(lSecond); 

  long lTime=lNewHour + lNewMinute + lSecond;  
  //long lTime=(lHour*10000) + (lMinute * 1000) + lSecond;  
  //long lTime=0;
  return lTime;
}

The output :
lHour=21
lMinute=15
lSecond=48
lNewHour=13392
lNewMinute=1500
lSecond=48

The compiler is doing integer (16 bit) calculations which overflowed giving you your strange results. You can fix it by putting an L suffix on your constants, or replace your int variables with long.

Melbfella:
I thought some very simple maths should achieve this, but alas, I'm stumped by the output. The value of 'lNewHour' should be 210000 (21 * 10000), yet it's coming back as 13392. The minute calculation seems to be working correctly (15*100=15000).

Looks like it is truncating, as wildbill said.

210000 is 0x33450

13392 is 0x3450

You lost the leading digit.

  long lNewHour=lHour*10000;

You are multiplying two ints so the compiler does int arithmetic. (This is by design).

Try:

  long lNewHour = 10000L * lHour;

Or make lHour a long. Or try this:

  long lNewHour = (long) lHour * 10000;

Thanks guys - the L suffix did the trick :slight_smile:

Melbfella:
I'm trying to get the current time from an RTC (ie 21:15:33) and return it as a long (ie 211533).

That is a pretty bizarre way to represent a time.

It would make more sense either to represent it as a string ("21:15:33" or "211533" or however you prefer) or as an absolute number of units since an epoch, such as seconds since midnight. At a pinch you could even store it as a set of byte values (0, 21, 15, 33) stored in a 4-byte long. (This is not what you're doing above.)