3 ms·
Or compile this with clang and -msse4.2 -O2 // https://codereview.stackexchange.com/questions/38182 // https://codereview.stackexchange.com/a/38184
by 1ris 8y ago
Or compile this with clang and -msse4.2 -O2
// https://codereview.stackexchange.com/questions/38182
// https://codereview.stackexchange.com/a/38184
// Definition: Count number of 1's and 0's from integer with bitwise operation
// 2^32 = 4,294,967,296
// unsigned int 32 bit
#include<stdio.h>
int CountOnesFromInteger(unsigned int);
int main()
{ unsigned int inputValue;
short unsigned int onesOfValue;
printf("Please Enter value (between 0 to 4,294,967,295) : ");
scanf("%u",&inputValue);
onesOfValue = CountOnesFromInteger(inputValue);
printf("\nThe Number has \"%d\" 1's and \"%d\" 0's",onesOfValue,32-onesOfValue); }
// Notice the popcnt
int CountOnesFromInteger(unsigned int value) {
int count;
for (count = 0; value != 0; count++, value &= value-1);
return count; }
- kwillets 8y agoI've seen this and others, but they're brittle. Terminating that count loop for any other reason, for example, will break it. There's another one for reversing bytes in an integer, but I ended up hard-coding the intrinsic due to brittleness.