Skip to content

Instantly share code, notes, and snippets.

@promovicz
Created June 20, 2019 02:14
Show Gist options
  • Save promovicz/1c73429c9cd1d110c523e7639356def1 to your computer and use it in GitHub Desktop.
Save promovicz/1c73429c9cd1d110c523e7639356def1 to your computer and use it in GitHub Desktop.
Counting bits with a compiler builtin
#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