Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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

.main() { char *p = "hello world!"; p[0] = 'H'; printf("%s",p); }

1248


What is hashing in c?

1118


What language is windows 1.0 written?

1006


Differentiate abs() function from fabs() function.

977


What should malloc() do?

1121


How can I swap two values without using a temporary?

1077


explain what is fifo?

1037


Is stack a keyword in c?

1052


What is scope rule of function in c?

1047


What is a pointer on a pointer in c programming language?

1109


Describe the complexity of Binary search, Quicksort and various other sorting and searching techniques..

1002


pgm to find number of words starting with capital letters in a file(additional memory usage not allowed)(if a word starting with capital also next letter in word is capital cann't be counted twice)

2299


How can I sort a linked list?

1004


What do you mean by a sequential access file?

1051


How are 16- and 32-bit numbers stored?

1259