Construction an logical expression which will count bits in a byte.

Posted by danatel on Stack Overflow See other posts from Stack Overflow or by danatel
Published on 2010-05-24T10:53:20Z Indexed on 2010/05/24 11:01 UTC
Read the original article Hit count: 162

Filed under:

When interviewing new candidates, we usually ask them to write a piece of C code to count the number of bits with value 1 in a given byte variable (e.g. the byte 3 has two 1-bits). I know all the common answers, such as right shifting eight times, or indexing constant table of 256 precomputed results.

But, is there a smarter way without using the precomputed table? What is the shortest combination of byte operations (AND, OR, XOR, +, -, binary negation, left and right shift) which computes the number of bites?

© Stack Overflow or respective owner

Related posts about toy-problem