Skip to content

Instantly share code, notes, and snippets.

@wffurr
Last active August 29, 2015 14:00
Show Gist options
  • Save wffurr/ef34dd66f990f249f9ea to your computer and use it in GitHub Desktop.
Save wffurr/ef34dd66f990f249f9ea to your computer and use it in GitHub Desktop.
Count bits in a 32-bit integer
#include<stdio.h>
#include<limits.h>
#include<math.h>
/** returns the number of 1 bits in x */
short countBits(int x) {
short count = 0;
int mask = 1;
for(short i = 0; i < sizeof(x); i++) {
if((mask & x) == mask) {
count++;
}
mask = mask << 1;
}
return count;
}
void runTest(int x, short expected) {
short actual = countBits(x);
if(actual != expected) {
printf("Error: Expected %d bits in %d, but counted %d.", expected, x, actual);
}
}
int main() {
runTest(0, 0);
runTest(1, 1);
runTest(2, 1);
runTest(3, 2);
runTest(((int)pow(2, 6))-1, 6);
runTest(INT_MAX, 31);
runTest(INT_MIN, 1);
printf("Run all tests!\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment