Skip to content

Instantly share code, notes, and snippets.

@rmccullagh
Created April 3, 2015 22:43
Show Gist options
  • Select an option

  • Save rmccullagh/1f5533ce3f2ba0ae6899 to your computer and use it in GitHub Desktop.

Select an option

Save rmccullagh/1f5533ce3f2ba0ae6899 to your computer and use it in GitHub Desktop.
C: Check if a number is a power of 2
#include <stdbool.h>
/*
* https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
*/
bool isPowerOf2(unsigned int x)
{
/*
* Convert # into binary
* If there is more than 1 "1", then
* it is NOT a power of 2
*
* Returns the number of 1-bits in x.
*/
if(__builtin_popcount(x) > 1) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment