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
What is the use of ?
Design a program which assigns values to the array temperature. The program should then display the array with appropriate column and row headings.
Write programs for String Reversal & Palindrome check
What does malloc () calloc () realloc () free () do?
Explain indirection?
Why isnt there a numbered, multi-level break statement to break out
What is the difference between array_name and &array_name?
Is c language still used?
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.
What is a union?
Explain that why C is procedural?
What are the types of macro formats?
What are pointers? What are stacks and queues?
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
What is restrict keyword in c?