What is the most efficient way to count the number of bits
which are set in a value?
Answer Posted / bryan w
Question needs clarification. What platform? There are
bitwise trick that are optimal for various platforms, but
you need to know if the value is 16 bit, 32 bit, 64 bit, 128
bit, or something else entirely.
The earlier three examples are all incorrect for operating
on signed integers; if a negative value is presented the
code will fail.
The most efficient portable human readable answer is to loop
over sizeof type * CHAR_BITS times, shift left and add one
if the bit is set.
On some platforms the most efficient way is to use a bit of
assembly (such as the POPCNT instruction if available) to
perform the operation for you.
Without either of those, there are simple classic algorithms
of &, |, and ^ to accumulate the bits and sum them. They
need to be adjusted to match the architecture's number of
bits. These routines may be inefficient on modern PCs with
long pipelines or out-of-order processing cores.
| Is This Answer Correct ? | 1 Yes | 2 No |
Post New Answer View All Answers
Which function in C can be used to append a string to another string?
What is bubble sort in c?
What is masking?
What is the difference between array and linked list in c?
Explain what is wrong with this program statement?
What is the significance of an algorithm to C programming?
What is the time and space complexities of merge sort and when is it preferred over quick sort?
write a program to generate address labels using structures?
Why do we use static in c?
Can a pointer be volatile in c?
What are the storage classes in C?
Does free set pointer to null?
What is 2c dna?
Why header files are used?
How arrays can be passed to a user defined function