Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this bitwise operation check for a power of 2?

I'm looking at some code which should be trivial -- but my math is failing me miserably here.

Here's a condition that checks if a number if a power of 2 using the following:

if((num != 1) && (num & (num - 1))) { /* make num pow of 2 */ } 

My question is, how does using a bitwise AND between num and num - 1 determine if a number is a power of 2?

like image 337
Coocoo4Cocoa Avatar asked Jun 27 '09 20:06

Coocoo4Cocoa


People also ask

How do you check if a number is a power of 2?

To check if a given number is a power of 2, we can continuously divide the number by 2, on the condition that the given number is even. After the last possible division, if the value of the number is equal to 1, it is a power of 2. Otherwise, it is not.

How can the Bitwise operator be used to find the power of 2 in C?

The power_of_2() function is used for finding the power of 2 using bit wise operators.

How do you tell if a number is a power of 2 in binary?

A power of two, when expressed in binary, will always look like 1 followed by n zeroes where n is greater than or equal to 0. Ex: Decimal Binary 1 1 (1 followed by 0 zero) 2 10 (1 followed by 1 zero) 4 100 (1 followed by 2 zeroes) 8 1000 (1 followed by 3 zeroes) . . . . . .

How do you find the Bitwise of two numbers?

The bitwise OR of two numbers is just the sum of those two numbers if there is no carry involved, otherwise you just add their bitwise AND. Let's say, we have a=5(101) and b=2(010), since there is no carry involved, their sum is just a|b.


1 Answers

Any power of 2 minus 1 is all ones: (2N - 1 = 111....b)

2 = 2^1.  2-1 = 1 (1b) 4 = 2^2.  4-1 = 3 (11b) 8 = 2^3.  8-1 = 7 (111b) 

Take 8 for example. 1000 & 0111 = 0000

So that expression tests if a number is NOT a power of 2.

like image 147
eduffy Avatar answered Oct 04 '22 09:10

eduffy