The tricks of bit computing are very interesting~

There are six basic bitwise operators: AND, OR, XOR, negation, shift left, and shift right:

Enter picture description here

Bit operation example operation

Bit operation Features Example
x >> 1 Remove the last digit 101101->10110
x << 1 Add a 0 at the end 101101->1011010
x << 1 Add a 1 at the end 101101->1011011
x|1 Change the last digit to 1 101100->101101
x & -2 Change the last digit to 0 101101->101100
x ^ 1 The last bit is negated 101101->101100
x | (1 << (k-1)) Turn the kth bit from the right to 1 101001->101101,k=3
x & ~ (1 << (k-1)) Turn the kth bit from the right to 0 101101->101001,k=3
x ^(1 <<(k-1)) The kth from the right is reversed 101001->101101,k=3
x & 7 Take the last three 1101101->101
x & (1 << k-1) Take the last k bits 1101101->1101,k=5
x >> (k-1) & 1 Take the kth from the right 1101101->1,k=4
x | ((1 << k)-1) Turn the last k bits into 1 101001->101111,k=4
x ^ (1 << k-1) Invert the last k bits 101001->100110,k=4
x & (x+1) Turn the consecutive 1s on the right into 0 100101111->100100000
x | (x+1) Turn the first 0 from the right into 1 100101111->100111111
x | (x-1) Turn the consecutive 0s on the right into 1 11011000->11011111
(x ^ (x+1)) >> 1 Take the consecutive 1s on the right 100101111->1111
x & -x Remove the left side of the first 1 from the right 100101000->1000
x&0x7F Take the last 7 100101000->101000
x& ~0x7F Is it less than 127 001111111 & ~0x7F->0
x & 1 Parity 00000111&1->1

Two considerations for using bit operations:

  1. Bit operations can only be used to reshape data. Bit operations on float and double types will be reported by the compiler.
  2. The operation priority of bit operators is relatively low, because try to use parentheses to ensure the order of operations

1. Determine whether a value is an integer power of 2

Problem-solving ideas:

There is only one 1 in the highest bit of the binary corresponding to the integer power of 2, such as: 8, the binary is 1000; 4, the binary is 0100,

Then subtract 1 from the number and perform the AND operation with the number. After subtracting 1, the binary is obtained: 7, the binary is 0111; 3, the binary is 0011, we can see that 8&7 is 0,

4&3 is 0

So, if n is an integer power of 2, then the result of n & (n-1) must be 0:

The value of n must be greater than 0 


1.  public class Main {

3.      public static void main(String[] args) {

4.          int n = 8;

5.          if ((n & (n-1)) == 0){

6.              System.out.println("整数的二次方 true");

7.          }else{

8.              System.out.println("不是整数的二次方");

9.          }

10.      }

11.  }

2. Use bit operation to exchange two numbers [Do not use intermediate variables]

XOR


1.  public class Main {

3.      public static void main(String[] args) {

4.          int n = 8, m = 10;

5.          n ^= m;

6.          m ^= n;

7.          n ^= m;

8.          System.out.println(n + ", " + m);

9.      }

10.  }

For example: a = 13, b = 6:
The binary of a is 13 = 8 + 4 + 1 = 1101 (binary)
The binary of b is 6 = 4 + 2 = 110 (binary)

  1. a ^= b a = 1101 ^ 110 = 1011;
  2. b ^ = ab = 110 ^ 1011 = 1101; Immediately b == 13
  3. a ^ = ba = 1011 ^ 1101 = 110; Immediately a == 6

Other methods, use addition and subtraction


1.  public class Main {

3.      public static void main(String[] args) {

4.          int n = 8, m = 10;

5.          n = n + m;

6.          m = n - m;

7.          n = n - m;

8.          System.out.println(n + ", " + m);

9.      }

10.  }

3. Calculate how many 1s are in the binary representation of a 32-bit integer

Use x & (x-1) to eliminate the last digit 1, and calculate how many times it has been eliminated.

Such as:

13: 1101

12: 1100

Phase and: 1100, eliminate the last digit


1.  public class Main {

3.      public static void main(String[] args) {

4.          // 计算在一个 32 位的整数的二进制表示中有多少个 1

5.          int m = 13, num = 0;

6.          while (true){

7.              if (m == 0) break;

8.              m &= (m-1);

9.              num ++;

10.          }

11.          System.out.println(num);

12.      }

14.  }

4. Positive numbers become negative numbers, or negative numbers become positive numbers

The conversion sign only needs to be reversed and then add 1


1.  public class Main {

3.      public static void main(String[] args) {

4.          // 计算在一个 32 位的整数的二进制表示中有多少个 1

5.          int m = -13;

6.          int changeM = ~m + 1;

7.          System.out.println(changeM);

8.      }

10.  }

5. Determine the parity of a value

As long as it is decided according to whether the least bit is 0 or 1, 0 means even number, 1 means odd number, so only need to AND 1.

Therefore, if ((a & 1) == 0) can be used instead of if (a% 2 == 0) to determine whether a is even.


1.  public class Main {

3.      public static void main(String[] args) {

4.          int m = -14;

6.          if ((m & 1) == 1){

7.              System.out.println("ji");

8.          }else{

9.              System.out.println("ou");

10.          }

11.      }

13.  }

6. Multiply by 2 to the power of m operation

The operation of multiplying by 2, that is, 2 to the power of 1, and shifting 1 bit to the left

System.out.println(10<<1);

 Derive the extension:

Multiplied by 2 to the power of m

System.out.println(10<<2); // 乘以 2的2次方,相当于乘以 4 

7. Divide by 2 operation (the operation of negative odd numbers is not available)

System.out.println(10>>1);

8. Convert to absolute value


1.  public class Main {

3.      public static void main(String[] args) {

4.          int n = 12;

6.          System.out.println(0 >> 31); // 0

7.          System.out.println(10 >> 31);  // 0

8.          System.out.println(-10 >> 31);  // -1

10.          System.out.println((n ^ (n >> 31)) - (n >> 31));  // 12 

12.      }

14.  }
  1. First: n>>31 get the sign of n

If n is a positive number, n>>31 is equal to 0; if n is a negative number, n>>31 is equal to -1. If n is a positive number, n^0-0 is unchanged;

  1. If n is a negative number n^-1, you need to calculate the complement of n and -1, and then take the complement after the exclusive OR. As a result, the sign of n changes and the absolute value is subtracted by 1, and then minus -1 is the absolute value

9. Determine whether the signs of the two numbers are the same

true means x and y have the same sign, false means x and y have opposite signs.

System.out.println((a ^ b) > 0);

10. Find the average of two integers (int)

System.out.println((a+b) >> 1);

11. Find the maximum of two integers


1.  int max(int a,int b){

2.      return b & ((a-b) >> 31) | a & (~(a-b) >> 31);

3.      /*如果a>=b,(a-b)>>31为0,否则为-1*/

4.  }

12. Find the minimum of two integers


1.  int min(int a,int b){

2.      return a & ((a-b) >> 31) | b & (~(a-b) >> 31);

3.      /*如果a>=b,(a-b)>>31为0,否则为-1*/

4.  }

13.  Addition of two integers

Use  ^ and to  & add two integers

  1. XOR of two numbers: It is equivalent to adding two numbers without considering carry;
  2. Two numbers are ANDed and shifted to the left by one position: equivalent to finding a carry;

Insert picture description here

Insert picture description here

13+11 = ?;

13 in binary 1 1 0 1 -----a 13

11 binary 1 0 1 1 -----b 11  

 (a&b) <<1  ->   1 0 0 1 0                         -----d         18

          a^b  ->     0 1 1 0                   -----e          6

 (d&e) <<1  ->   0 0 1 0 0                       ------f         4

          d^e  ->  1 0 1 0 0                  -----g        20

 (f&g) <<1  ->   0 1 0 0 0                       ------h        8

          f^g  ->  1 0 0 0 0                   ------i           16

 (h&i) <<1 -> 0  0 0 0 0                       ------h 0 ---- -------- There is no carry, then exit the loop

          h^i  ->  1 1 0 0 0                  ------i           24


1.  private static int getSum(int a, int b) {

2.      if (a == 0) return b;

3.      if (b == 0) return a;

4.      while (b != 0) {

5.          int carry = a & b; // 得到有进位的位置

6.          a = a ^ b; // 直接相加,但是没有进位

7.          b = carry << 1; // 得到进位

8.      }

9.      return a;

10.  }

Project recommendation:

More than 2000 G of electronic resource sharing in various computer industries (continuous update)

2020 WeChat Mini Program Full-stack Project-Miaomiao Making Friends [With courseware and source code]

Spring Boot develops a small and beautiful personal blog [with courseware and source code]

Java microservices actual combat 296 episodes of large-scale video-Grain Mall [with code and courseware]

Java development microservices Changbu Mall actual combat [full 357 episodes of large projects]-with code and courseware

The most complete and detailed data structure and algorithm video-[with courseware and source code]​​​​​​​

Insert picture description here

Guess you like

Origin blog.51cto.com/14906631/2608802