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


Please Help Members By Posting Answers For Below Questions

What does struct node * mean?

606


What is function and its example?

632


How do you define a string?

662


any function have arguments one or more OR not . it is compulsary a) any function compulsary have one or more arguments b) any function did not have arguments. It is not compulsary c) it is optional it is not compulsary d) none of the above

649


c language interview questions & answer

1465






how much salary u want ? why u join in our company? your domain is core sector why u prefer software ?

1510


What is union and structure?

578


explain what is a newline escape sequence?

694


Is it possible to use curly brackets ({}) to enclose single line code in c program?

806


Is the exit() function same as the return statement? Explain.

668


What are the two forms of #include directive?

649


What does void main return?

612


Explain about block scope in c?

667


Why static variable is used in c?

564


Explain how can I remove the trailing spaces from a string?

632