A simple example of a Java bitwise operation of shift bit and or or or or)

  • 2020-04-01 01:30:18
  • OfStack


public class Test { 
    public static void main(String[] args) { 
        //1. Left shift (<<)
        // 0000 0000 0000 0000 0000 0000 0000 0101  And then the left 2 After bit, the low position complement 0 : // 
        //0000, 0000, 0000, 0000, 0000, 0000, 0001, 0100 is 20 in base 10
        System.out.println(5 << 2);//The result is 20

        //2. Right shift (>> ) high complement sign bit
        //0000, 0000, 0000, 0000, 0000, 0000, 0000, 0000, 0000, 0101 and then move 2 places to the right, and the higher position will be filled with 0:
        // 0000 0000 0000 0000 0000 0000 0000 0001 
        System.out.println(5 >> 2);//The result is 1

        //3. Unsigned right shift (>>> ) add 0 to the high position
        //For example, when -5 is converted into binary, it is 0101, and the negative addition of 1 is 1011
        // 1111 1111 1111 1111 1111 1111 1111 1011 
        //We shifted 5 to the right by 3, -5 to the right by 3, and unsigned to the right by 3:
        System.out.println(5 >> 3);//The result is 0
        System.out.println(-5 >> 3);//The result is 1
        System.out.println(-5 >>> 3);//The result is 536870911

        //4. Bit and (&)
        //Bit and: the NTH bit of the first operand is the NTH bit of the second operand
        System.out.println(5 & 3);//The result is 1
        System.out.println(4 & 1);//The result is 0

        //5, bit or (|)
        //The NTH bit of the first operand is in the NTH bit of the second operand as long as one of them is 1, the NTH bit of the result is also 1, otherwise it's 0
        System.out.println(5 | 3);//The results of 7

        //6. Heterotopic or (^)
        //The NTH bit of the first operand is opposite to the NTH bit of the second operand, so the NTH bit of the result is also 1, otherwise it is 0
         System.out.println(5 ^ 3);//Results for 6  

        //7. Bit non (~)
        //If the NTH bit of the operand is 1, the NTH bit of the result is 0, and vice versa.
        System.out.println(~5);//Results for - 6  
    }  
}

Related articles: