This is the 11th day of my participation in Gwen Challenge
I believe that many new brothers more or less understand the concept of bit computing, but in the actual business development is rarely used
In this paper, the author will summarize the application techniques of bit operation provided by the gods
Not professional, but can be applied in the code
introduce
Without further elaboration of the academic concepts, you can briefly think of bitwise operations as calculations of each bit in binary
To understand and use bitwise operations, we need the following skills:
- Convert decimal to binary
- Familiar with bitwise operators
plan
Suppose we have two variables, height = 181 and weight = 76
Decimal to binary
Convert height to binary as follows:
- 181 divided by 2 is 90 with a remainder of 1
- 2 goes into 90 45 times and has a remainder of 0
- 2 goes into 45 22 times and has a remainder of 1
- 22 divided by 2 is 11 and has a remainder of 0
- 2 goes into 11 5 times and has a remainder of 1
- 5 divided by 2 goes into 2 and has a remainder of 1
- 2 divided by 2 is 1 and has a remainder of 0
- 1 divided by 2 has a remainder of 1
The remainder is read from bottom up and the height binary is 10110101
The process can be summarized as dividing the data by 2, and then continuing to divide by 2 using the quotient until the quotient is 0, and inverting the remainder is the binary result
using<<
and>>
Multiply and divide by 2
This is pretty straightforward once we know how to use binary
<< is a left shift operation, the binary moves to the left, and the data is naturally larger (equivalent to multiplying by 2): weight << 1 = 152
Height >> 1 = 90
use^
Implement variable exchange
First, clarify two concepts:
- Any binary
^
Self, all of them are equal to0000000...
- Any binary
^ 00000...
Is equal to itself
So, we swap height and weight:
height ^= weight
weight ^= height
height ^= weight
Copy the code
It might be complicated to write it this way, but let’s expand it out:
height = height ^ weight = 181 ^ 76
weight = weight ^ height = 76 ^ (181 ^ 76) = 76 ^ 76 ^ 181 = 181
height = height ^ weight = (181 ^ 76) ^ 181 = 181 ^ 181 ^ 76 = 76
Copy the code
Looking at the above expansion operation, at the beginning of the two clear concepts, is the idea very clear?
use&
Judge parity
So let’s go back to binary, binary parity is easy, just to see if the last digit is 1
So, we can judge in this way:
if (0 == (height & 1)) {
// This is even
} else {
// This is odd
}
Copy the code
conclusion
Don’t swap height and weight in real life. You won’t have a girlfriend