Skip to content

Instantly share code, notes, and snippets.

@zedr
Created January 5, 2022 17:18
Show Gist options
  • Save zedr/9d9a1f4c19495b14a6b2b11205251f87 to your computer and use it in GitHub Desktop.
Save zedr/9d9a1f4c19495b14a6b2b11205251f87 to your computer and use it in GitHub Desktop.
Simple bit counter for 32bit integers
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int
count_bits(int n)
{
int l, c;
l = 0;
c = 0;
while (l < 32) {
if (n & (1 << l++)) {
c++;
}
}
return c;
}
int main(int argc, char *argv[])
{
int n, c;
if (argc != 2) {
fprintf(stderr, "Usage: %s NUMBER\n", *argv);
return 1;
}
n = atoi(*(argv+1));
if (n < 0) {
fprintf(stderr,
"Number too large. Must be lower than %ld\n",
(long) INT_MAX + 1);
return 1;
}
c = count_bits(n);
printf("%d: %d\n", n, c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment