Search code examples
javabit-manipulationsigned

Bitwise operator ~ giving the ouput not expected


I wrote a simple program in which I have a bitwise operator which gives the signed value in java. But when I do so it returns a value higher different than the original value.

class bit
{

public static void main(String[] args)
{


int j=10;

System.out.println("jjjj"+~j);

}

}

Gives the output has:

-11. Which the expected output should be -9. What is the problem?


Solution

  • 0000 1010 // = 10 i.e binary representation of 10
    1111 0101 // = ~10 i.e inversion of bits
    

    Negative numbers are stored in 2's complement form. Check this for details

    0000 1011 // = 11 i.e binary 11
    1111 0100 // inversion of bits
    1111 0101 // 2's complement of 11 = -11
    

    Thus,

    ~10 = -11