Overflowing of Unsigned Int

前端 未结 3 1379
死守一世寂寞
死守一世寂寞 2020-11-28 12:43

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

相关标签:
3条回答
  • 2020-11-28 13:10

    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.

    0 讨论(0)
  • 2020-11-28 13:21

    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;
    
    0 讨论(0)
  • 2020-11-28 13:25

    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.

    0 讨论(0)
提交回复
热议问题