posted 12 years ago
Hi guys,
public class Flip{
public static void main(String argv[]){
System.out.println(~4);
}
}
can anybody explain why the output of this program is 5.
Thanks in advance
Good guy
public class Flip{
public static void main(String argv[]){
System.out.println(~4);
}
}
can anybody explain why the output of this program is 5.
Thanks in advance
Good guy
posted 12 years ago
To combine and extend what David and Ernest said...
If we just look at 16 bits 4 = 0000000000000100. The ~ does a one's complement operation, so ~4 = 1111111111111011. The  does a two's complement operation, which is the one's complement plus 1, so 4 = 1111111111111100. Since 5 = 0000000000000101, 5 = 1111111111111011, which is the same things as ~4.
Why use two's complement for negative numbers? Because it makes subtraction work. For instance let's try 5 + (4): 0000000000000101 + 1111111111111100 = 0000000000000001 with a 1 bit that got carried off the left end. With the one's complement, the answer is off by one.
One other clever thing about two's complment is that 0 = 0, while ~0 != 0.
Ryan
[ April 26, 2005: Message edited by: Ryan McGuire ]
If we just look at 16 bits 4 = 0000000000000100. The ~ does a one's complement operation, so ~4 = 1111111111111011. The  does a two's complement operation, which is the one's complement plus 1, so 4 = 1111111111111100. Since 5 = 0000000000000101, 5 = 1111111111111011, which is the same things as ~4.
Why use two's complement for negative numbers? Because it makes subtraction work. For instance let's try 5 + (4): 0000000000000101 + 1111111111111100 = 0000000000000001 with a 1 bit that got carried off the left end. With the one's complement, the answer is off by one.
One other clever thing about two's complment is that 0 = 0, while ~0 != 0.
Ryan
[ April 26, 2005: Message edited by: Ryan McGuire ]
There are 10 kinds of people in this world. Those that understand binary get this tiny ad:
The WEB SERVICES and JAXRS Course
https://coderanch.com/t/690789/WEBSERVICESJAXRS
