GILGAMESH
GILGAMESH

Reputation: 1856

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;

Upvotes: 21

Views: 29007

Answers (3)

Pubby
Pubby

Reputation: 53047

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;

Upvotes: 29

user1192284
user1192284

Reputation: 1

It probably depends a bit on your compiler. I had errors like this years ago, and sometimes you would get runtime error, other times it would basically "wrap" back to a really small number that would result from chopping off the highest level bits and leaving the remainder, i.e if it's a 32 bit unsigned int, and the result of your multiplication would be a 34 bit number, it would chop off the high order 2 bits and give you the remainder. You would probably have to try it on your compiler to see exactly what you get, which may not be the same thing you would get with a different compiler, especially if the overflow happens in the middle of an expression where the end result is within the range of an unsigned int.

Upvotes: -3

evandrix
evandrix

Reputation: 6210

Unsigned integer overflow, unlike its signed counterpart, exhibits well-defined behaviour.

Values basically "wrap" around. It's safe and commonly used for counting down, or hashing/mod functions.

Upvotes: 7

Related Questions