Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflowing of Unsigned Int

What will the unsigned int contain when I overflow it? To be specific, I want to do a multiplication with two unsigned ints: what will be in the unsigned int after the multiplication is finished?

unsigned int someint = 253473829*13482018273;
like image 539
GILGAMESH Avatar asked Feb 08 '12 13:02

GILGAMESH


People also ask

What happens when int overflows?

An integer overflow is a type of an arithmetic overflow error when the result of an integer operation does not fit within the allocated memory space. Instead of an error in the program, it usually causes the result to be unexpected.

How do you find the overflow of an unsigned addition?

When two signed 2's complement numbers are added, overflow is detected if: both operands are positive and the sum is negative, or. both operands are negative and the sum is positive.

How do you prevent an overflow int?

One very good way to prevent integer overflows is to use int64_t to implement integers. In most case, 64-bits ints will not commit overflow, unlike their 32-bits counterparts. There is actually very few downsides in using int64_t instead of int32_t .

What is the max value of unsigned int?

The number 4,294,967,295, equivalent to the hexadecimal value FFFF,FFFF16, is the maximum value for a 32-bit unsigned integer in computing.


1 Answers

unsigned numbers can't overflow, but instead wrap around using the properties of modulo.

For instance, when unsigned int is 32 bits, the result would be: (a * b) mod 2^32.


As CharlesBailey pointed out, 253473829*13482018273 may use signed multiplication before being converted, and so you should be explicit about unsigned before the multiplication:

unsigned int someint = 253473829U * 13482018273U;
like image 99
Pubby Avatar answered Oct 05 '22 05:10

Pubby