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;

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

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.