Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I work around what seems to be integer overflow despite the type being large enough

I am performing the following calculation:

unsigned long long int interval = (ui->spinBox_2->value() * 60 * 60 * 1000) + (ui->spinBox_3->value() * 60 * 1000) + (ui->spinBox_4->value() * 1000) + (ui->spinBox_5->value());

What it’s basically doing is taking in the hours, minutes, seconds, and milliseconds and converting it all to milliseconds.

Example:
1 hour 0 minutes 2 seconds 100 milliseconds

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

= (1 * 60 * 60 1000) + (0 * 60 * 1000) + (2 * 1000) + (100)

If I put 999 hours for example, it outputs 18446744073010984420 milliseconds
when it should output 3596400000 milliseconds.

The type is unsigned long long int, which should be able to store up to 18446744073709551615, which is significantly bigger than the calculation.

Is there a way to fix this, or an alternative way to save the time in milliseconds rather than calculating and storing it in an unsigned long long int variable?

>Solution :

The promotion to an unsigned long long happens on assignment. your calculation however happens as ints so the calculation overflows before it has a chance to be unsigned long long.

You can either cast your operands to unsigned long long or use a ULL suffix to make them unsigned long long : 60ULL

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading