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
How can I call a function with an argument list built up at run time?
What is variable declaration and definition in c?
Write a C Program That Will Count The Number Of Even And Odd Integers In A Set using while loop
What is the use of volatile?
write an algorithm to display a square matrix.
The difference between printf and fprintf is ?
What is define c?
please can any one suggest me best useful video tutorials on c i am science graduate.please help me.u can email me to sas29@in.com
What is the value of a[3] if integer a[] = {5,4,3,2,1}?
Explain main function in c?
What is the size of empty structure in c?
What is pivot in c?
Tell us something about keyword 'auto'.
What is a char c?
What are # preprocessor operator in c?