0

I have two unsigned 32 bit integers, call them x and y. I want to periodically increment the two uint32's by seemingly random uint32 values. x and y will accumulate and I want them to continue to accumulate until they hit their limit, at which point I want them to start back at 0 + the value they would have had added had they not overflowed.

Assume the code looks like:

//This would be called, say every 5 seconds
void increment_vals(uint32_t *x, uint32_t *y, uint32_t x_inc, uint32_t y_inc)
{
    *x += x_inc;
    *y += y_inc;

    if (x overflowed || y overflowed)
    {
        *x = x_inc;
        *y = y_inc;
    }
}

So basically my question is: how do I know when x OR y has overflowed and need to to be reset? Should I just store x and y before incrementing and if the result is less than the original value then it must have overflowed? Is that guaranteed?

Thanks.

shauryachats
  • 9,975
  • 4
  • 35
  • 48
srau
  • 73
  • 1
  • 7

3 Answers3

1

You could check for overflow before incrementing:

if(x_inc > (MAXINT - *x)) {
    //about to overflow
}
Eamonn McEvoy
  • 8,876
  • 14
  • 53
  • 83
1

I suggest

uint32_t xx = *x + x_inc;
if (xx < *x)
     *x = 0;
else *x = xx;
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

I found this document quite helpful and descriptive in answering my question, particularly page 172:

"For unsigned integers, if the sum is smaller than either operand, an overflow has occurred."

srau
  • 73
  • 1
  • 7