Skip to content

Instantly share code, notes, and snippets.

@keyvan
Created March 18, 2012 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keyvan/2067682 to your computer and use it in GitHub Desktop.
Save keyvan/2067682 to your computer and use it in GitHub Desktop.
Find if an integer is a power of 2 in C without libraries
The below code is an efficient function to find if an integer number is a power of 2 in C without using any libraries. It would be good to think why it's efficient.
int IsPowerOfTwo(int x) {
while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */
x /= 2;
return (x == 1);
}
@keyvan
Copy link
Author

keyvan commented Mar 18, 2012

As a follower on Twitter pointed out (@mshonle), a better way is to use bit operations that I never thought about. I was drown in short-circuiting the conditional branch in there!

The code can be simplified like this:

return (x & (x - 1) == 0);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment