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 is the use of ?

612


Design a program which assigns values to the array temperature. The program should then display the array with appropriate column and row headings.

1757


Write programs for String Reversal & Palindrome check

592


What does malloc () calloc () realloc () free () do?

548


Explain indirection?

633






Why isnt there a numbered, multi-level break statement to break out

581


What is the difference between array_name and &array_name?

768


Is c language still used?

528


The purpose of this exercise is to benchmark file writing and reading speed. This exercise is divided into two parts. a). Write a file character by character such that the total file size becomes approximately >10K. After writing close the file handler, open a new stream and read the file character by character. Record both times. Execute this exercise at least 4 times b). Create a buffer capable of storing 100 characters. Now after generating the characters, first store them in the buffer. Once the buffer is filled up, store all the elements in the file. Repeat the process until the total file size becomes approximately >10K.While reading read a while line, store it in buffer and once buffer gets filled up, display the whole buffer. Repeat the exercise at least 4 times with different size of buffer (50, 100, 150 …). Records the times. c). Do an analysis of the differences in times and submit it in class.

1624


What is a union?

601


Explain that why C is procedural?

648


What are the types of macro formats?

596


What are pointers? What are stacks and queues?

571


a direct address that identifies a location by means of its displacement from a base address or segment a) absolute address b) relative address c) relative mode d) absolute mode

643


What is restrict keyword in c?

635