Checking for powers of two

Submitted by:J Kamy81

Date added:11 May, 2017

Category:C++

The following code uses bitwise operators to determine if an unsigned integer, x, is a power of two.

Tags: integer , determine

Code Snippet:

/* The following code uses bitwise operators to determine 
if an unsigned integer, x, is a power of two. If x is a power of two, x is represented in binary
with only a single bit; therefore, subtraction by one removes that bit and flips all the
lower-order bits.

then effectively checks to see if any bit is the
same. If not, then it's a power of two.*/

int powerOfTwo(unsigned int x)
{
return !((x-1) & x);
}
 
 

Comments