Created
June 20, 2019 02:14
-
-
Save promovicz/1c73429c9cd1d110c523e7639356def1 to your computer and use it in GitHub Desktop.
Counting bits with a compiler builtin
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 <stdlib.h> | |
#include <stdio.h> | |
int main(int argc, char **argv) { | |
unsigned word; | |
int count; | |
/* check for argument */ | |
if(argc < 2) { printf("Usage: %s INTEGER\n", argv[0]); abort(); } | |
/* convert argument */ | |
word = (unsigned)atoi(argv[1]); | |
/* count number of 1-bits */ | |
count = __builtin_popcount(word); | |
/* print result */ | |
printf("1-bits: %d\n", count); | |
/* this never fails */ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment