~ operator

The following code gives me 14 for j..... but i don't know how....

class Test

{

public static void main(String args[])

{

int j;

int i;

i = 0xFFFFFFFF1;

System.out.println("i is " + i);

j = ~i;

System.out.println("j is "+j);

}

}

please help me in solving it manually.......

[359 byte] By [Sundar.nagarathinama] at [2007-11-27 3:50:03]
# 1

This does not compile!

>i = 0xFFFFFFFF1;

I think you've put one 'F' to many.

i, in binary form, would be:

1111 1111 1111 1111 1111 1111 1111 0001

Now, negative numbers are represented in 2's complement form.

So when you use this value it woud be first changed to:

0000 0000 0000 0000 0000 0000 0000 1110 //1's compement

0000 0000 0000 0000 0000 0000 0000 1111 //add 1 to make 2's complement

This is 15, but since it was originally negative, it'll be printed as -15. That's the first part; i is -15.

Now, when you apply the '~', it simply flips all the bits. So,

1111 1111 1111 1111 1111 1111 1111 0001

would become

0000 0000 0000 0000 0000 0000 0000 1110 //the one's complement mentioned earlier

And that's why you get j is 14.

nogoodatcodinga at 2007-7-12 8:53:57 > top of Java-index,Java Essentials,New To Java...
# 2

Hex 0xFFFFFFF1 == Bin 11111111111111111111111111110001

~i ==

~11111111111111111111111111110001 ==

11111111111111111111111111110001 ^ 11111111111111111111111111111111 ==

00000000000000000000000000001110 ==

14 (decimal)

Message was edited by:

prometheuzz

Christ I'm slow again...

prometheuzza at 2007-7-12 8:53:57 > top of Java-index,Java Essentials,New To Java...
# 3
thank u very much
Sundar.nagarathinama at 2007-7-12 8:53:57 > top of Java-index,Java Essentials,New To Java...