Last active
August 29, 2015 14:00
-
-
Save wffurr/ef34dd66f990f249f9ea to your computer and use it in GitHub Desktop.
Count bits in a 32-bit integer
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<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