The connection between bitwise AND operation (&) and remainder operation (%)

Performance comparison

Remainder operation: a % b is equivalent to the operation of a - (a / b) * b
Bitwise AND operation: it is an instruction of the CPU
In what special scenarios, the AND operation & can be used instead of the remainder operation % to improve efficiency Woolen cloth?
When performing the remainder operation on 10, we found that the remainder is always the number on the one digit in the integer, regardless of what other bits are;
in the bitwise AND operation, we often need to use the bit operator & to get The value of some bits, for example, use 0xff&0x17ae to get the value 0xae of the lower 8 bits, if the range of the result value of the remainder is exactly [0, the base of the remainder (b in a%b)] set (the set elements are only 0 is the same as b) , then the lower bit is the result of the remainder.
Example: 23%16 == 7 is equivalent to 0x17 & 0x0F == 0x07. Therefore, when the remainder of the power of 2 needs to be calculated, the & operator can be used instead, and the efficiency will be much improved. When x = 2^n (n is a natural number), a % x = a & (x - 1).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326092504&siteId=291194637