aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Bitwise Operator ~ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Bitwise Operator ~" Watch "Bitwise Operator ~" New topic
Author

Bitwise Operator ~

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I'm trying to understand how to apply bitwise ~ operator into coding.
I understand that bitwise operator invert the bits, such as: from 00001111 to 11110000.
this is my code:
class bitwise {
public static void main(String args[]) {
int x = 1;
x = ~x;

System.out.println(x);
}
}
the output is -2. why?
Greg Whelan
Ranch Hand

Joined: May 18, 2000
Posts: 52
I'll answer your question with a question... how is (int)-1 represented in 2's complement notation? What is ~-1?
Vivek Shrivastava
Ranch Hand

Joined: Jun 03, 2000
Posts: 277
There is a short cut for these type of problems (i found it here only so thanks to this site) :
int x = 1;
~x = - (x+1)
This is derived from 2's complement of a number.
Hope this will help you.
vivek
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Hie,
You just said that you know this operator inverts the bits, that is 0's become 1's and vice versa. So it is really a matter of applying the operator to see how ~1 become -2.
a.1 has the bit pattern 000......1
b.If you invert this bit pattern, what do you get ? youget
111......0
I think may be your trouble starts here, but it should not.This is your answer, but the question is, what is it's value in decimal notation ?To get its decimal value, you have first to note that the most significant bit (MSM) is set, that is it is 1.When you have a number like this, to get its decimal value you follow these steps
a. invert the bits:so 111.....0 becomes 000.....1
b.add 1 to the result: so 000....1 becomes 000....10
This is the absolute value of your answer.But you know it is negative because you inverted the MSB which was 1. so this pattern is for the value 2, and applying the sign we have -2.
Hope this helps,
Herbert.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Thanks, guys, that helps alot...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Bitwise Operator ~