This week's book giveaway is in the Kotlin forum.We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Bitwise Operator ~

Anonymous
Ranch Hand
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
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
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.
vivek

Herbert Maosa
Ranch Hand
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
Posts: 18944
Thanks, guys, that helps alot...