File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# ~ question required

PETER CARTER
Ranch Hand

Joined: Aug 28, 2004
Posts: 70
public class test {
public static void main(String[] args) {
int x=6;
System.out.println(~x);
}
}
Why print :-7 ??
Thanks!
Mohit Agarwal
Ranch Hand

Joined: Mar 30, 2004
Posts: 88
Hi ,
The reason is 6 is written in binary of 32(000.....110) bits , then all the bits are complemented(111........001) which makes it negative number.
Using 2s complement notation(flip all bits and add 1) you will get -7.
Hope u understand.

Tom Tolman
Ranch Hand

Joined: Sep 02, 2004
Posts: 83
An int is a 32 bit value represented as 2's complement. Some simple values to MEMORIZE:

1 = 0x00000001 = 000000000000000000000000000001
-1 = 0xffffffff = 111111111111111111111111111111
0 = 0x00000000 = 000000000000000000000000000000

Now 6 is equal to 0x00000006 or
00000000000000000000000000000110 (4 + 2)
Invert this, and you get
11111111111111111111111111111001

What is this in decimal? Well, if you don't want to memorize an equation, walk through the negative numbers

00000000000000000000000000000000 = 0
11111111111111111111111111111111 = -1
11111111111111111111111111111110 = -2
11111111111111111111111111111101 = -3
11111111111111111111111111111100 = -4
11111111111111111111111111111011 = -5
11111111111111111111111111111010 = -6
11111111111111111111111111111001 = -7

Or if you prefer, you can memorize an equation- do you see the relationship between the above numbers and the positive numbers?

To go from negative to positive, you invert the bits and add one
To go from positive to negative, you invert the bits and add one (1 inverted is 11111111111111111111111111111110, and you need to add one to get to 11111111111111111111111111111111)

So now you are inverting the bits on the number six. You have not added one. If you did add one, you would have -6. So -6 missing 1 is -7.
VINCE CARTER
Greenhorn

Joined: Sep 26, 2004
Posts: 13
int x=6;
System.out.println(~x+1);
The result is :-6

int x=-6;
System.out.println(~(x-1));
The result is :6

Thanks!!!

I agree. Here's the link: http://aspose.com/file-tools

subject: ~ question required