1

I want to convert hour to seconds but unsigned long is overflowing, here's the code:

#include <Wire.h>
#include <DS3231.h>

RTClib myRTC;
unsigned long seconds;
char timestr[9];

void setup() {
  Serial.begin(250000);
  Wire.begin();
}

void loop() {
  DateTime now = myRTC.now();

  snprintf(timestr, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
  seconds = (now.hour() * 3600);
  Serial.println(timestr);
  Serial.println(seconds);
  delay(100);
}

And the console output is:

16:33:36
4294959360

Why is this happening?

5

It's not the unsigned long that's overflowing but the calculation that you're assigning to it.

3600 is a signed integer (by default), and now.hour() is an unsigned byte. The unsigned byte gets promoted to match the "largest" type in the calculation - a signed integer - and then the calculation is performed, resulting in a signed integer.

That signed integer is then assigned to an unsigned long and, if the result is negative (as it may well be - 10*3600 > 32767) you end up with a massive number.

The simple "cure" is to ensure that one value in the calculation is an unsigned long. And the best way of doing that is to make your constant an unsigned long: by appending "UL" to it:

seconds = (now.hour() * 3600UL);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.