Skip to content

Instantly share code, notes, and snippets.

@zflat
Last active October 15, 2018 17:21
Show Gist options
  • Save zflat/b692df71a164f46fbad286c8b85bdab5 to your computer and use it in GitHub Desktop.
Save zflat/b692df71a164f46fbad286c8b85bdab5 to your computer and use it in GitHub Desktop.
sum the bits of an integer
#include <stdio.h>
#include <stdlib.h>
unsigned long bit_sum(unsigned long n) {
return n ? (1 + bit_sum(n & (n - 1))) : 0;
}
void main(int argc, char ** argv) {
char * p;
long n;
if(argc < 2) {exit(EXIT_FAILURE);}
n = strtol(argv[1], &p, 0); // see strotol manpage for error checking
if(*argv[1] == '\0' || *p != '\0') {exit(EXIT_FAILURE);}
printf("%ld\n", bit_sum(n));
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment