1
public class bitwise_operator {

    public static void main(String[] args) {

        int var1 = 42;
        int var2 = ~var1;
        System.out.println(var1 + " " + var2); 
   }
}

The above code produces 42 -43 as the output.

As far as my understanding goes, Unary Not operator (~), inverts all of the bits of its operand.

Now, 42 in binary is 00101010. On using ~ operator, we get inverted value of 42 i.e. 11010101

If you convert the preceding binary value, the output should be something else and not -43

Tried my luck with different numbers to observe the pattern and found that, the output is 1 number more than the initial value supplied with a leading (-) sign before it, as seen in the above case.

For eg..,

if num is 45           // Output is 45 -46
if num is 1001        // Output is 1001 -1002

Could someone please explain how the Unary Not Operator (~) works internally to output such results?

Radiodef
  • 37,180
  • 14
  • 90
  • 125
mindfreak
  • 456
  • 3
  • 9
  • 29
  • 2
    check [this](http://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work) question – SomeJavaGuy Apr 16 '15 at 13:33
  • *"the output is 1 number more than the initial value supplied with a leading (-) sign"* This hypothesis is correct, but it's usually seen as the other way around. A unary negation is achieved by flipping all the bits and adding one. So e.g. if you want to turn `42` in to `-42` you do `~42 + 1`. – Radiodef Apr 16 '15 at 13:38

2 Answers2

3

You are using a signed integer value which is in 2's complement.

Your result is correct: 11010101 is in fact -43:

-2^7 + 2^6 + 2^4 + 2^2 + 2^0 = -128 + 64 + 16 + 4 + 1 = -128 + 85 = -43

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
  • 2
    See also [JLS § 15.15.5.](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.5): "In all cases, ~x equals (-x)-1." – Robin Krahl Apr 16 '15 at 13:37
  • @lentz - **`Thanks, that's what I was looking out for !!!`** thanks, once again... – mindfreak Apr 16 '15 at 13:58
  • @lentz - **`just to clarify, in case of (~) the calculation begins with the highest bit having`** **(-)** **`sign to it and rest of the digit has the default positive sign, is that the pattern we follow` ??** – mindfreak Apr 16 '15 at 14:08
  • It is not specific for the ~ operator but for all signed integer in 2's complement: For n bits bn, bn-1,..,b0 is: -2^bn + (2^bn-1 + 2^bn-2 + .. + 2^b0). See more here: http://en.wikipedia.org/wiki/Two%27s_complement – Ori Lentz Apr 16 '15 at 14:10
  • @RobinKrahl - **Phenomenal, that was as good as I wanted !!** – mindfreak Apr 16 '15 at 14:13
0

This is what's known as two's complement, and it is how integers and all fixed point numbers in Java, C, C++ etc work

-x = ~x + 1

So for example -1 (0xFFFF) negated bitwise (0x0) plus 1 = 0x1

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80