Detail the bitwise operator of Java

  • 2020-10-23 20:07:24
  • OfStack

The bit operator of Java is used to manipulate a single "bit" (bit) in the basic data type of an integer, that is, the decimal bit. And we know that bits are 0's and 1's, so bitwise operations are basic operations on the data. If a value of type char, byte, or short is shifted, it is converted to type int and then shifted

Bitwise operator for Java

The bitwise operator performs Boolean algebra on the bitwise of the two parameters, resulting in 1 result. This operator has the difference between ( & ), not (~), or (|), xor (^). We know that the unit "bits" (bit), that is, the decimal bits, are both 0 and 1, and the xor (^) may be a bit more complicated, in two operand bits, the same result is 0, the different result is 1. So the basic logic would look something like this.

1 & 1-11 & So 0 goes to 0, 0 goes to 0, 0 goes to 11|, 1 goes to 11|, 0 goes to 11 to the 0 goes to 1 (1 is 01, 0 is 00, so it's 01, 1) 1 to the 1 goes to 0

Shift operator for Java

The shift operator of Java is nothing more than a shift to base 2.

for < < So we're going to move to the left, so we're going to move all of base 2 to the left one place, 0010, 0000 < < 1 is equal to 0100, 0000

for > > We're going to move to the right, so we're going to move all of base 2 to the right by 1 bit, 0010, 0000 > > 1 is equal to 0001, 0000.

Try the following example, where integer values are also converted to base 2:


class Test{
  public static void main(String[] args){
  int numInt1 = 3;
  int numInt2 = -3;
  System.out.println(numInt1<<1);
  System.out.println(numInt1>>1);System.out.println(numInt2<<1);
 System.out.println(numInt2>>1);

 } 
 }/*  The output is as follows (www.breakyizhan.com)
6   ---> 0000 0011<<1 ,  into 0000 0110
1   ---> 0000 0011>>1 ,  into 0000 0001...1 At the back of the 1 It's pushed out, so it's going to be zero 1
-6   --> 1111 1101<<1 ,  into 1111 1010  The not +1= 0000 0110 -6
-2   --> 1111 1101>>1 ,  into 1111 1110  The not +1= 0000 0010 -2 
*/

Of course, there is also Java's 3 yuan operator, this part of the function and if-ES47en a little similar, more details can be seen in:

The $3 operator for Java

conclusion


Related articles: