0 day streak
3. Complexity and mathOverflow and two’s complement

Overflow and two’s complement

Overflow is what happens when a result is too big to fit in the fixed number of bits an integer has. Like a car’s odometer rolling from 999999 back to 000000, an unsigned integer wraps around to zero. Signed integers are stored in two’s complement, a scheme where the top bit counts as a large negative value, so the same adder handles positive and negative numbers and going past the maximum lands on the most negative value. In C and C++, unsigned wraparound is defined, but signed overflow is undefined behavior, meaning the compiler may assume it never happens. Overflow bugs hide in averaging two large indexes, long-running counters and size checks attackers can exploit.

In this lesson: An integer wheel that wraps.