Integer overflow concept

瘦欲@ 提交于 2019-12-02 13:26:44
Sunsetquest
   DecVal   BinVal
    11   -> 1011
XOR 5    -> 0101
           -------
    14   -> 1110

fyi, This does not really have anything to do with int overflow.

Since you're asking about wrap-around I'm answering that below. But as is clear from comments, you really tried the C++ expression 11^5, a bitlevel XOR, and got the answer 14, which has nothing to do with wraparound. The XOR result of each pair of bits is 0 if they're the same value, and 1 if they're different.


Now, in the following ^ denotes exponentiation; it's a common notation for that.

11^5 = 161051.

Now consider a situation where 16 bits are used to represent integers, and there's only magnitude, no sign. I.e. a 16-bit unsigned C++ integer type. Then there are 2^16 possible bit patterns, and they are numbered 0 through 2^16 - 1, and represent those numbers.

161051 is larger than the largest possible value of that 16-bit type. If it were 2^16 exactly it would correspond to 0 (called wrap-around), if it were 2^16 + 1 it would correspond to 1, and so on. So it corresponds to 161051 - 2^16.

Now if that in turn also was greater than 2^16 - 1 you would repeat the process.

And this produces the remainder of integer division by 2^16.

Essentially it correspond to just removing all the bits except the 16 least significant ones.

By the way the result for this example is not any of your choices (a), (b), (c) or (d).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!