Question

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?

Was it helpful?

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

OTHER TIPS

If we look at the binary for the number 10 we can see

0000 0000 0000 0000 0000 0000 0000 1010

Where the first 0 is the signing bit.

If we now flip the binary INCLUDING the signing bit, we get:

1111 1111 1111 1111 1111 1111 1111 0101

Which... if you consider that java uses signed integers, is -11.

If we get away from signed numbers for a second and just consider the value of a 4-byte unsigned integer that is ~10 we get the value of: 4294967285.

To convert a unsigned integer to a two's complement signed integer we subtract the value of 2^32 from the integer if its over 2^31 - 1.

2^32 - 4294967285 = -11

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top