JAVA based bit operation

Note: JAVA bit operation is often encountered when reading JDK source code, so it is very necessary to learn about bit operation. Before learning, you need to know about binary code. Here are some related articles: Source code, complement, inverse code

First of all, we all know that the bit operators defined in JAVA can be applied to integer types (int), long, short, char, and byte types.

There are seven bit operators in Java:

Bitwise Operators explain
>> Shift right operator: the value on the left side of the symbol shifts the number of bits specified by the value on the right side of the symbol by bits. If it is a positive number, the high number is supplemented by 0, and if it is a negative number, the high number is supplemented by 1
<< Shift left operator: the value on the left of the symbol shifts the number of bits specified by the value on the right of the symbol by bits, and complements 0 in the low order
>>> Unsigned shift right operator: the value on the left side of the symbol shifts the number of bits specified by the value on the right side of the symbol by bits, regardless of positive and negative high bits, and 0 is added
& The and (AND) operator performs Boolean algebra on the corresponding bits in two integer operands. When both bits are 1, it outputs 1, otherwise 0
| Or operator, which performs Boolean algebra on the corresponding bits of two integer operands. As long as one of the two bits is 1, it outputs 1, otherwise it is 0
^ The XOR operator performs Boolean algebra on the corresponding bits in two integer operands. If the two bits are equal, it is 0 and if they are not equal, it is 1
~ Non (NOT) operator, bitwise negation operator flips each bit of the operand, that is, 0 becomes 1 and 1 becomes 0

Example code of seven bitwise operators:

/**
 * @Auther: csp1999
 * @Date: 2020/10/26/11:33
 * @Description: Bit operator
 */
public class bit_operators {

    @Test
    public void test01() {
        // int max = Integer.MAX_VALUE;
        // int min = Integer.MIN_VALUE;
        int num1 = -20;
        int num2 = 30;
        int bit_operator_1 = num1 << 1;// A positive number shifted n bits to the left expands by 2^(n) times, and a negative number shifted n bits to the left shrinks by 2^(n) times
        int bit_operator_2 = num1 >> 1;// A positive number shifted to the right by N bits is reduced by 2^(n) times, and a negative number shifted to the right by N bits is expanded by 2^(n) times
        int bit_operator_3 = num1 >>> 1;// Unsigned right shift remember to understand that the binary stored in the computer is stored in the form of complement
        int bit_operator_4 = num1 & num2;
        int bit_operator_5 = num1 | num2;
        int bit_operator_6 = num1 ^ num2;
        int bit_operator_7 = ~num1;

        // System.out.println(max);
        // System.out.println(min);
        // System.out.println("0"+Integer.toBinaryString(Integer.MAX_VALUE));
        // System.out.println(Integer.toBinaryString(20));
        System.out.println(bit_operator_1);
        System.out.println(bit_operator_2);
        System.out.println(bit_operator_3);
        System.out.println(bit_operator_4);
        System.out.println(bit_operator_5);
        System.out.println(bit_operator_6);
        System.out.println(bit_operator_7);
    }
}

The calculation results are as follows:

-4
-1
2147483647
2
-2
-4
1

Principle analysis (high 0 is manually supplemented for easy viewing)

a = 11111111 11111111 11111111 11101100
b = 00000000 00000000 00000000 00011110
------------------------------------------------
a << 1	-->	11111111 11111111 11111111 11011000
a >> 1	-->	11111111 11111111 11111111 11110110
a >>> 1	-->	01111111 11111111 11111111 11110110	
a & b 	= 	00000000 00000000 00000000 00001100
a | b 	= 	11111111 11111111 11111111 11111110
a ^ b 	= 	11111111 11111111 11111111 11110010
~a		= 	00000000 00000000 00000000 00010011

During bit operation, except for long type, other types will be automatically converted to int type. After conversion, the length of the acceptable right operand is 32. When performing bit operations, short integer and byte values are always converted into integer values before shifting.

data type size
byte 8 bit
short 16 bit
char 16 bit
int 32 bit
long 64bit

Example:

byte num1 = -128;
byte num2 = 63;
byte bit_operator_1  = (byte)(a << 1);
byte bit_operator_2  = (byte)(a >> 1);
byte bit_operator_3  = (byte)(a >>> 1);
byte bit_operator_4  = (byte)(a & b);
byte bit_operator_5  = (byte)(a | b);
byte bit_operator_6  = (byte)(a ^ b);
byte bit_operator_7  = (byte)(~ a);

The type of the above code is automatically promoted to int after bit operation, so we need to use variables of type int to accept it. However, we can perform forced conversion after bit operation, but the forced conversion directly intercepts bytes, resulting in loss of accuracy. The final results are as follows:

0
-64
-64
0
-65
-65
127

For int type integer shift num1 > > num2, when b > 32, the system first uses num2 to remainder 32 (because int is 32 bits), and the result is the number of bits of the real shift. For example, num1 > > 33 and num1 > > 1 have the same result, while num1 > > 32 = num1;

The usage scenarios of bit operation are as follows:

1. Judge parity

@Test
public void test02() {
    Integer num = 123;
    // Common method 1 for judging parity:
    if (num % 2 == 0) {
        System.out.println("even numbers");
    } else {
        System.out.println("Odd number");
    }
    // Operation mode 2 for judging odd and even bits:
    if ((num & 1) == 0) {
        System.out.println("even numbers");
    } else if ((num & 1) == 1) {
        System.out.println("Odd number");
    }
}

The lowest bit of an even number must be 0, the lowest bit of an odd number must be 1, and the lowest bit of 1 is 1. All other bits are zero. When performing an and operation:

  • Even number: A & 1 = = 0
  • Odd number must: A & 1 = = 1

2. Do not use intermediate variables to exchange two numbers

@Test
public void test03() {
    int a = 10;
    int b = 20;
    // 1. Exchange two values depending on intermediate variables:
    int c;
    c = a;
    a = b;
    b = c;
    System.out.println("a=" + a + ",b=" + b);
    // 2. The bit operation does not use intermediate variables to exchange two numbers:
    a = 10;
    b = 20;
    a = a ^ b;
    b = b ^ a;
    a = a ^ b;
    System.out.println("a=" + a + ",b=" + b);
}

Here are two things to know:

  1. Any number and its own XOR operation result is 0
  2. XOR conforms to the commutative law, that is, a ^ b = b ^ a

OK, then the above code operation is equal to:

a = a ^ b;
b = b ^ a = b ^ (a ^ b) = a;
a = a ^ b = (a ^ b) ^ (b ^ (a ^ b)) = (a ^ b) ^ a = b;

3. Judge whether a positive integer is an integer power of 2

public boolean power(int num) {
    if (num <= 0) {
        System.out.println("Negative numbers are not calculated here. They are returned directly false");
        return false;
    } else {
        return (num & (num - 1)) == 0;
    }
}
@Test
public void test04() {
    int num = 1024;
    System.out.println(power(num));
}

If any positive integer is an idempotent of 2, it is shaped as follows:

10
100
1000
10...0
1234

That is, if the first digit is 1 and the next digit is 0, then after subtracting 1, they are all shaped as follows:

01
011
0111
01...1
1234

Therefore, the idempotent of 2 greater than zero and the number minus one must be 0

4. Symmetric encryption

It is to use XOR encryption once and XOR decryption twice:

@Test
public void test5(){
    String a = "sadfsdfsdfhfghf123dfgfg";
    System.out.println(a);
    int key = 324545231;
    byte[] bytes = a.getBytes();
    for (int i = 0; i < bytes.length-1; i++) {
        bytes[i] = (byte)(bytes[i] ^ key);
    }
    String b = new String(bytes);
    System.out.println(b);

    for (int i = 0; i < bytes.length-1; i++) {
        bytes[i] = (byte)(bytes[i] ^ key);
    }
    String c = new String(bytes);
    System.out.println(c);
}

Print results:

sadfsdfsdfhfghf123dfgfg
����������������������g
sadfsdfsdfhfghf123dfgfg

The above are the basic examples and knowledge points of JAVA bit operation. Similarly, bit operation is also widely used in JDK source code. For small partners who first learn JDK source code, the basic knowledge of bit operation is needed. Finally, I recommend a treasure blogger:[ date bread]

Posted by TheJoey on Tue, 10 May 2022 08:52:52 +0300