-3

What is the best way to count the number of 1's in an 32-bit integer x in C without using for or while loops, and without using constants greater than 0xFF?

What I thought of is shifting x 24 to the right and count how many 1's in the shifted integer and store that in a variable count. And then, shifting x 16 to the right and increment count by the number of 1's in the shifted integer, and so on.

So, any ideas of a better solution?

Hammam A
  • 15
  • 5

1 Answers1

1

You can tabulate the number of 1's in all d bits numbers. This takes a table of 2^d entries, each not exceeding the value d (<255).

Now you can cut your number in slices of d bits and lookup the counts for all slices.

A good compromise between space/number of operations is probably with d=4 (8 slices, table size=16).