2

I was looking for some bit-Operations in Java and found the ~ operator. I found following explenation:

~a results from a, by inverting all bits of a

So when I make a System.out.println(~1), why is the output -2? As 0001 = 1 after inverting it should be 1110

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
forty4seven
  • 73
  • 1
  • 4

1 Answers1

2

Just remember that negative numbers are stored in two's complement representation. So that means you first take the complement of the number and then add 1.

int val = 20;
val = (~val)+1;
//  20     ==   0b00000000000000000000000000010100
// ~20     ==   0b11111111111111111111111111101011
// (~20)+1 ==   0b11111111111111111111111111101100 
System.out.println(val);

Prints

-20

And whether the value is an integer or floating point, the high order bit is the sign bit. 1 means negative, 0 means not negative.

WJS
  • 36,363
  • 4
  • 24
  • 39