Last active
June 7, 2016 19:06
-
-
Save cschamp/6251371 to your computer and use it in GitHub Desktop.
This is a solution that an interview candidate gave when I asked him to write a function to count the number of 1-bits set in a byte. The interview was for a position at Nimble Storage.
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 <stdlib.h> | |
int nbits(unsigned char value); | |
int testtab[] = { | |
0x53, | |
0xaa, | |
0x55, | |
0x01, | |
0x00, | |
0xf0, | |
0xff, | |
0xef, | |
0x33, | |
0x03 | |
}; | |
#define NTESTS (sizeof testtab / sizeof testtab[0]) | |
int main(int argc, char **argv) | |
{ | |
int i; | |
for (i = 0; i < NTESTS; i++) { | |
printf("nbit(0x%0.2x) == %d\n", testtab[i], nbits(testtab[i])); | |
} | |
exit(0); | |
} | |
/* | |
* Count the number of 1-bits set in a byte. | |
*/ | |
int nbits(unsigned char value) | |
{ | |
value = ((value & 0xaa) >> 1) + (value & 0x55); | |
value = ((value & 0xcc) >> 2) + (value & 0x33); | |
value = ((value & 0xf0) >> 4) + (value & 0x0f); | |
return value; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment