Saturday, April 21, 2018

c - Count bits in the number




Duplicate:





Best algorithm to count the number of set bits in a 32-bit integer?







Suppose you have a number. Is there any way to count the bits which equals to 1 in binary representation of that number, not using iteration? I mean, is there any way to do it in constant time using some bitwise operators and masks. I need solution which will work well for both architectures 32 bit and 64 bit. Ah almost forgot, I need it for C language or assembler is also good.


Answer



There is a bit counting algorithm without a loop at http://graphics.stanford.edu/~seander/bithacks.html. Lots of bit counting algorithms at http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...