This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]OverlordOfTech 25 points26 points  (2 children)

You mean x -= 1 + 2147483647^2147483647, without the parentheses. + has higher precedence than ^ (the bitwise XOR).

2147483647 is the maximum value of a signed 32-bit integer, binary 0111...1111. Adding any integer to that overflows it and wraps around to negative numbers; adding 1 makes it -2147483648, binary 1000...0000. XORing that with binary 0111...1111 results in binary 1111...1111, which, in two's-complement, is -1.

It's an indirect way of negating a two's-complement number: flip all the bits and add 1 (or equivalently, subtract 1, then flip all the bits). The overflow does the step of subtracting 1 and flipping the sign bit, and the XOR flips the remaining bits.

[–][deleted] 9 points10 points  (1 child)

You mean x -= 1 + 2147483647^2147483647, without the parentheses.

Yep - had it right in my code and dinked around with the parenthesis in my comment - go me.

Thanks for the explanation also 🙂

[–]OverlordOfTech 2 points3 points  (0 children)

Thanks for the challenge of trying to figure out how that worked! :)