Bit computing topics for

Chit recently and people, met some of the more clever bit computing play

1, how to determine a number N is a power of 2?

Bloggers first reaction is-bit computing, but how to turn left and shift is a problem. (Cycle divided by 2, the result has been greater than 1 before the remainder of course be zero, but the efficiency ah.)

Here if the number is n, only n & (n-1) = 0, can determine this number N is a power of 2

2, how to obtain a number N nearest power of 2, such as 7-> 8,9> 16,19-> 32 this.

In fact, hashmap source, the answer has been given, the following excerpt:

 static final int tableSizeFor(int cap) {
        int n = none - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

 Because int is the maximum value of 2 ^ 32-1, things actually do here is to first extend the first 1 to second place, the first two extends to the top four, and so on in.

Guess you like

Origin www.cnblogs.com/fbw-gxy/p/11165983.html