programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# ~ question required

Ranch Hand
Posts: 70
• Number of slices to send:
Optional 'thank-you' note:
public class test {
public static void main(String[] args) {
int x=6;
System.out.println(~x);
}
}
Why print :-7 ??
Thanks!

Ranch Hand
Posts: 88
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 83
• Number of slices to send:
Optional 'thank-you' note:
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.

Greenhorn
Posts: 13
• Number of slices to send:
Optional 'thank-you' note:
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!!!