Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 271
Narek Margaryan Avatar asked Jan 14 '13 21:01

Narek Margaryan


3 Answers

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
like image 186
Carl Norum Avatar answered Sep 27 '22 19:09

Carl Norum


It does OR operations on negative numbers the same way it does so on positive numbers. The numbers are almost certainly represented in two's-complement form, which gives you these values:

 17 = 0000000000010001
-15 = 1111111111110001

As you can see, all the bits of 17 are already set in −15, so the result of combining them is again −15.

like image 33
Rob Kennedy Avatar answered Sep 27 '22 19:09

Rob Kennedy


A bitwise or with a negative number works JUST like a bitwise or with a positive number. The bits in one number are ored with the bits in the other number. How your processor represents negative numbers is a different matter. Most use something called "two's complement", which is essentially "invert the number and add 1".

So, if we have, for simplicity, 8 bit numbers:

15 is            00001111
Inverted we get  11110000
Add one          11110001

17 is            00010001

Ored together    11110001
like image 45
Mats Petersson Avatar answered Sep 27 '22 18:09

Mats Petersson