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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Bear Bibeault
• Liutauras Vilda
Sheriffs:
• Jeanne Boyarsky
• Junilu Lacar
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Jj Roberts
• Tim Holloway
• Piet Souris
Bartenders:
• Himai Minh
• Carey Brown
• salvin francis

# Bitwise complement operator

Greenhorn
Posts: 7
K&B page 175.
------------------------------------------------
class Bitwise{
public static void main(String[] args){
int x =5;
System.out.println("x is initially "+x);
x = ~x;
System.out.println("~x is equal to "+x);
}
}
-------------------------------------------------
prints:
x is initially 5
~x is equal to -6

could anyone explain why it is printing -6?

appreciate it,

Ranch Hand
Posts: 163
5(decimal =0000 0000 0000 0000 0000 0000 0000 0101(binary)
~5 = 1111 1111 1111 1111 1111 1111 1111 1010 (interchanged 1's & 0's)

Left most bit is '1' i.e. it is a -ve no. To find the Decimal equivalent of a negative binary number
step 1: find 1's complement
step 3: find the decimal equiavalent & put -ve sign

step 1: 0000 0000 0000 0000 0000 0000 0000 0101
step 2: 0000 0000 0000 0000 0000 0000 0000 0101 +1 =
0000 0000 0000 0000 0000 0000 0000 0110

step3 : 1* (2 to the power of 1) + 1 * ( 2 to the power of 2)
= (1 *2) + (2 * 2) = 2+4 = 6
put -ve sign i.e. -6

Therefore ~5=-6

got it?
[ January 03, 2006: Message edited by: Naresh Kumar ]

Abdi Duale
Greenhorn
Posts: 7
Yes I got it.

Thanks a lot Naresh. appreciate it

Ranch Hand
Posts: 411
Hello Abdi Duale,
Naresh has given very good explanation. Tip for ~ calculation, to save the time during the actual exam.

~x = - (x+1)
So ~5 = - (5+1) = -6
and ~-5 = -(-5+1) = 4

author
Posts: 9000
19
...and for those of you keeping score, this is a 1.4 topic, but NOT a 1.5 topic!

Abdi Duale
Greenhorn
Posts: 7
Thanks a lot for the tip Jay.
Appreciate it.

Greenhorn
Posts: 18
Jay that was a Good One

Cheers

 Consider Paul's rocket mass heater.