# Bitwise Operator ~

Anonymous

Ranch Hand

Posts: 18944

posted 15 years ago

- 0

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?

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

Vivek Shrivastava

Ranch Hand

Posts: 277

Herbert Maosa

Ranch Hand

Posts: 289

posted 15 years ago

- 0

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.

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

It is sorta covered in the JavaRanch Style Guide. |