This page was translated from Spanish with AI. The original version is in Spanish: read the original.

Integer Overflow

February 24, 20252 minutes

Why is 4294967295 + 1 equal to 0? You will find out in this post...

Integer Overflow

You can use this script to put the explanation into practice

/*gcc main.c -o main*/

#include <stdio.h>

int main() {
    int a, b, result;

    printf("> ");
    scanf("%d %d", &a, &b);

    result = a + b;

    printf("%d + %d = %d\n", a, b, result);

    return 0;
}

Numbers (int) in C are stored in 32-bit registers. Knowing this, we can conclude that the largest number you can store is 2147483647, since in binary 2147483647 is 31 ‘1’s, and the last bit is a 0 because it is a positive number.

>>> n = 2147483647
>>> b = format(n, 'b')
>>> print(f"{len(b)} - {b}")

31 - 1111111111111111111111111111111

Following on from this, the smallest number you can store is -2147483648, since in binary -2147483648 is a ‘1’ indicating that it is negative, followed by 31 ‘0’s

>>> n = 2147483648
>>> b = format(n, 'b')
>>> print(f"{len(b)} - {b}")
32 - 10000000000000000000000000000000

The problem arises when a very large number that takes up more than 32 bits is entered

[d3bo@archlinux integer_overflow]$ ./main
> 5000000000 0
705032704 + 0 = 705032704

The number 5000000000 was entered, but the program stored it as 705032704

Why?

The number 5000000000 in binary is 100101010000001011111001000000000 and takes up 33 bits, so it can’t be stored in full and the program truncates it

>>> n = 5000000000
>>> b = format(n, 'b')
>>> print(f"{len(b)} - {b}")
33 - 100101010000001011111001000000000
>>> print(f"{len(b[-32:])} - {b[-32:]}")
32 - 00101010000001011111001000000000

Truncating 100101010000001011111001000000000 to 32 bits leaves the number 00101010000001011111001000000000, which in decimal is 705032704

>>> print(int(b[-32:], 2))
705032704