How does C++ do bitwise "or" operations on negative numbers?

Narek Margaryan picture Narek Margaryan · Jan 14, 2013 · Viewed 12.1k times · Source

When I give to a variable such value: e = 17|-15; , I get -15 as an answer after compiling.I can't understand what arithmetic c++ uses. How does it perform a bit-wise OR operation on negative decimals?

Answer

Carl Norum picture Carl Norum · Jan 14, 2013

It's just doing the operation on the binary representations of your numbers. In your case, that appears to be two's complement.

 17 -> 00010001
-15 -> 11110001

As you can see, the bitwise OR of those two numbers is still -15.

In your comments above, you indicated that you tried this with the two's complement representations, but you must have done something wrong. Here's the step by step:

 15 ->  00001111      // 15 decimal is 00001111 binary
-15 -> ~00001111 + 1  // negation in two's complement is equvalent to ~x + 1
-15 ->  11110000 + 1  // do the complement
-15 ->  11110001      // add the 1