0
  1. If I have binary number 0111000111111, Is there any fast algorithm to count the number of 1 ?

  2. If 0111000111111 is a string(e.g "0111000111111") Is there any fast algorithm to count the number of 1 in the string?

1 Answers1

2

A relatively fast way is to precompute a table of the bit counts for all byte values and to sum for the four bytes of the (unsigned) integer.

byte NB[256]= { 0, 1, 1, 2, 1, 2, 2, 3, 1, 1, ... };

N= NB[U & 255] + NB[(U >> 8) & 255] + NB[(U >> 16) & 255] + NB[(U >> 24) & 255];

You can adapt this for different numbers of bits per slice.