Created
April 3, 2015 22:43
-
-
Save rmccullagh/1f5533ce3f2ba0ae6899 to your computer and use it in GitHub Desktop.
C: Check if a number is a power of 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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