#include <stdlib.h> #include <stdio.h> #include <inttypes.h> uint32_t count_nonzero_bits(uint32_t n) { uint32_t masks[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF }; size_t i; for(i=0; i < 5; i++) { n = (n & masks[i]) + ((n >> (1 << i)) & masks[i]); } return n; } uint32_t count_nonzero_bits_slow(uint32_t n) { uint32_t cnt=0; uint8_t tmp=0; while(n>0) { tmp = n&1; cnt += tmp; n >>= 1; } return cnt; } int main() { srand(time(0)); uint32_t iter, X; for (iter=0; iter<1000; iter++) { X=rand(); if (count_nonzero_bits(X)!=count_nonzero_bits_slow(X)) printf("test failed (number=%u)\n", X); } printf("tests finished\n"); return 0; }
enjoy!
No comments:
Post a Comment