File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

~ question required

 
PETER CARTER
Ranch Hand
Posts: 70
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class test {
public static void main(String[] args) {
int x=6;
System.out.println(~x);
}
}
Why print :-7 ??
Thanks!
 
Mohit Agarwal
Ranch Hand
Posts: 88
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 83
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic