Yesterday's article analyzing the principle of HashMap mentioned that the use of bit operations to replace modulo operations is efficient, but bit operations can only replace % operations in specific scenarios.
Under normal circumstances:
```` a % b = a - (a / b)*b ````
However, if the value of b is 2 to the nth power (n is a natural number), then the bit operation can be used instead of the modulo operation, and the
conversion is as follows:
```` a % b = a & (b-1) ````
The binary of 2 to the nth power is as follows:
```` ` 0001 2^0 1 0010 2^1 2 0100 2^2 4 1000 2^3 8 ````
It can be seen from the above that shifting one bit to the left is to zoom in by 2 times, and shifting one bit to the right is
to
```` 0000 2^0-1 0 0001 2^1-1 1 0011 2^2-1 3 0111 2^3-1 7 ````
For example,
we calculate the modulus of 11% 8,
the binary of 11 is: 1011
into the above formula:
```` 11 % 8 = 11 & (8-1) ````
The binary of 7: 0111
do & (and) operation for both, recall the operation rules:
```` & and. All 1s are 1s, all 0s are 0s. Any number and 0 are equal to 0. | or. All 1s are 1s, all 0s are 0s. Any number and 0 or are equal to the original value. ~ not. bit-by-bit negation ^ XOR. The same is 0, the difference is 1. Any number that is XORed with 0 is equal to the original value. ````
Result:
1011 & 0111 = 0011
is converted into decimal = 3,
so 11%8=3
This method is only suitable for finding N times of dividing a number by two. It is correct. The process of finding the modulus is 2^n- The number of 1 in 1 is the value of n, and then do the & operation with a, and the low bit obtained is the remainder we expect.
If you have any questions, you can scan the code and follow the WeChat public account: I am the siege division (woshigcs), leave a message in the background for consultation. Technical debts cannot be owed, and health debts cannot be owed. On the road of seeking the Tao, walk with you.
![](http://dl2.iteye.com/upload/attachment/0104/9948/3214000f-5633-3c17-a3d7-83ebda9aebff.jpg)