[Basics] Bit and operation and remainder

Regarding the bit and operation & and the remainder
today, when studying the hashmap source code, I found that when solving the entry distribution in the source code, most people thought that index = hash% length would be used, but the source code used index = hash & ( lenth -1).

/**

  • The default initial capacity - MUST be a power of two.
    */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

In addition, it can be noted from the above that in the definition of the entry array capacity in the source code, the capacity must be 2 to the n power (or 0), so I searched for the purpose.

The original bitwise AND can also be used to take the remainder, but there is a condition: the divisor must be 2 to the power of n. An example to illustrate:

9%8=1
1001 & (
1000-1 ) =1001 & 0111
=1 // 1001 is the binary representation of 9, and 1000 is the binary representation of 8.

In fact, it is obvious that in binary calculations, it is well known that a number shifted by 1 bit to the right is equivalent to the quotient of dividing by 2, and the bit that happens to be removed is the remainder obtained by dividing by 2, for example:

9 >> 1
=1001 >> 1
=100 | 1
=4 余 1

Moreover, not only dividing by 2, but dividing a number k by the nth power of 2, which is equivalent to shifting k to the right by n bits, and the n bits that are shifted out are exactly what we require to be the remainder.

Then the problem is simple. In fact, for the n-th power of the divisor, we only need to get the low n bits of the dividend, and just for the n-th power of 2, we convert it After it is binary, it is the number whose n+1 bit is 1, and the other low bits are all 0. Therefore, we subtract 1 from it, and we get a number whose n+1 bit is 0 and the other bits are 1. Use The bitwise AND operation between this number and the dividend k will get the low n-bit binary number of the dividend, which is
the result of k%2n.

Summary:
If a number m satisfies: m=2n

Then k% m = k & (m-1)

Guess you like

Origin blog.csdn.net/qq_33632004/article/details/106114743