Integer overflow concept

百般思念 提交于 2019-12-03 00:42:07

问题


How int overflow works. I mean to ask what would be the final result of an integer value if an overflow happens? I need to understand it on paper. Like I'm given a multiple choice question:

11^5 Produces:
a. 12
b. 14
c. 15
d. 17.

I know the answer is (b)14, but want to know why?


回答1:


   DecVal   BinVal
    11   -> 1011
XOR 5    -> 0101
           -------
    14   -> 1110

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




回答2:


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).



来源:https://stackoverflow.com/questions/30360335/integer-overflow-concept

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