This week's book giveaway is in the Android forum. We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line! See this thread for details.

Hi,
package Samples;
public class Byte1
{
public static void main(String[] a)
{
byte x = 3;
x = (byte)~x;
System.out.println(x);
}
}

I expected the output to be 12, but the output is -4. I know the operator ~ provides the 1's complement. But I could not interpret the output. Can anyone help?

Ilakya Mukunth wrote:Hi,
package Samples;
public class Byte1
{
public static void main(String[] a)
{
byte x = 3;
x = (byte)~x;
System.out.println(x);
}
}

I expected the output to be 12, but the output is -4. I know the operator ~ provides the 1's complement. But I could not interpret the output. Can anyone help?

Can you explain to us why you expected the output to be 12?

Ilakya Mukunth wrote:The bit pattern for 3 is 0011. The 1;s complement is 1100. The decimal value of this is 12.

First, a byte is 8 bits long -- not four bits. Second, Java uses twos complement to store numbers -- which I have to ask, do you know how to interpret twos complement numbers?

Henry

Ilakya Mukunth
Ranch Hand

Joined: Mar 13, 2012
Posts: 57

posted

0

I do not know java uses 2's complement to store the number. :-(
I know how to find 2's comp for a given number. (Add 1 to LSB to the 1's complement of the given number)
Can you please explain how the ~ operator works? I would be great help.

Ilakya Mukunth wrote:I do not know java uses 2's complement to store the number. :-(
I know how to find 2's comp for a given number. (Add 1 to LSB to the 1's complement of the given number)
Can you please explain how the ~ operator works? I would be great help.

Well, you explained everything already. And you are correct in that regard, so I don't know what you are confused with.

First, as you already mentioned, the ~ operator negates all the bits (also known as 1's complement). So....

3 = 0000 0011

which means

~3 = 1111 1100

The resultant byte is a negative number as the sign bit is a one. There is actually a formula to see what this value is, but the easiest way is to take the twos complement of it to see what the positive version of this number is...

And, as you already mentioned, to do that, negate and add one. So...

X = 1111 1100

Negate X = 0000 0011
Negate X plus one = -X = 0000 0100 = 4

And since negative X equals four, X (the pre twos complement number) must have been -4.

Jeanne Boyarsky wrote:This would probably be a good time to make sure you are aware that ~ is not on the exam. Bit operations were removed from the SCJP.

Thanks for the info. Yes I knew its not there in OCPJP. But just curious to know

Ilakya Mukunth
Ranch Hand

Joined: Mar 13, 2012
Posts: 57

posted

0

Jeanne Boyarsky wrote:This would probably be a good time to make sure you are aware that ~ is not on the exam. Bit operations were removed from the SCJP.

I believe even the shift operators are removed from the OCPJP. is it so?