Summary of the shift operator in Java

  • 2020-04-01 02:21:24
  • OfStack

There are three types of shift operators in Java

< <           :         Left shift operator, num < < 1 is the same thing as num times 2

> >           :         Right shift operator, num > > 1 is the same thing as num over 2

> > >       :         Move to the right unsigned, ignore the sign bits, and fill the empty Spaces with 0

Now let's see how these shift operations are used. Okay



package com.b510.test;

public class Test {
    public static void main(String[] args) {
        int number = 10;
        //Primitive binary
        printInfo(number);
        number = number << 1;
        //The left one
        printInfo(number);
        number = number >> 1;
        //Moves to the right one
        printInfo(number);
    }

    
    private static void printInfo(int num){
        System.out.println(Integer.toBinaryString(num));
    }
}

The running result is:

1010
10100
Let's align the above results:

43210           Digits -- -- -- -- -- -- -- --
  1010           Decimal: 10        The original number                 number
10100           Decimal: 20& PI;       Move one digit to the left             Number = number < < 1;
  1010           Decimal: 10        Right shift one digit & cake;           Number = number > > 1;

 

After watching the demo above, do you know a lot about left and right shifts

For: > > >

  Move to the right unsigned, ignore the sign bits, and fill the empty Spaces with 0

The value > > > Num        -     Num specifies the number of digits to move the shift value value.

The only thing to remember about the rule of unsigned right shift is that the sign bit extension is ignored, and zero completes the highest bit & PI; Unsigned right shift operator > > > It only makes sense for 32-bit and 64-bit values


Related articles: