Search code examples
pythonc++bit

How can we decide that an integer is power of 2 by using bit manipulation?


For example if the given number n = 16 If it is power of 2 then the output should be true else false, i want the answer by using bit manipulation.


Solution

  • The solution mentioned by @TimRoberts is the most simple way of using bit manipulation.

    Just check if (n & (n - 1) == 0). Why does this work?

    Assume n = 8 (1000 in base 2), then n - 1 = 7 (0111 in base 2). If you do a bitwise AND of these two, you get 0. This is true for n equal to any power of 2.

    So you function should simply be:

    bool is_power_of_2(unsigned long n)
    {
        return n != 0 && (n & (n - 1)) == 0;
    }