Expressing the power of 2

suggest change

To express a power of two (2n) that fits in an int, a left shift can spell out n.

The syntax is basically:

int pow2 = 1<<n;

Examples:

int twoExp4 = 1<<4; //2^4
int twoExp5 = 1<<5; //2^5
int twoExp6 = 1<<6; //2^6
...
int twoExp31 = 1<<31; // bit pattern of 2^31, which as a signed int is Integer.MIN_VALUE

This is especially useful when defining constant values that should make it apparent, that a power of 2 is used, instead of using hexadecimal or decimal values.

int twoExp4 = 0x10; //hexadecimal
int twoExp5 = 0x20; //hexadecimal
int twoExp6 = 64; //decimal
...
int twoExp31 = -2147483648; //is that a power of 2?

A simple method to calculate the int power of 2 would be

int pow2(int exp){
    // For an int, only the low 5 bits of exp are used.
    return 1<<exp;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents