All Puzzles: Here
Puzzle: Devise a fast algorithm for computing the number of 1-bits in an unsigned integer. If the machine supports n-bit integers, can we compute the number of 1-bits in O(log n) machine instructions? Can we compute the number of 1-bits in O(b) machine instructions where b is the number of 1-bits in the integer?
Source: Commonly asked in job interviews for Software Engineers. I first heard it in 1996 when I was a graduate student.
Solution: This article presents six solutions to this problem. Source code in C is available.
1) Iterated Count
int bitcount (unsigned int n) {
int count = 0;
while (n) {
count += n & 0x1u;
n >>= 1;
}
return count;
}
|
Iterated Count runs in time proportional to the total number of bits. It simply loops through all the bits, terminating slightly earlier because of the while condition. Useful if 1’s are sparse and among the least significant bits.
2a) Sparse Ones
int bitcount (unsigned int n) {
int count = 0 ;
while (n) {
count++ ;
n &= (n - 1) ;
}
return count ;
}
|
Sparse Ones runs in time proportional to the number of 1 bits. The mystical line n &= (n – 1) simply sets the rightmost 1 bit in n to 0.
2b) Dense Ones
int bitcount (unsigned int n) {
int count = 8 * sizeof(int) ;
n ^= (unsigned int) - 1 ;
while (n) {
count-- ;
n &= (n - 1) ;
}
return count ;
}
|
Dense Ones runs in time proportional to the number of 0 bits. It is the same as Sparse Ones, except that it first toggles all bits (n ~= -1), and continually subtracts the number of 1 bits from sizeof(int).
Sparse Ones and Dense Ones were first described by Peter Wegner in “A Technique for Counting Ones in a Binary Computer”, Communications of the ACM, Volume 3 (1960) Number 5, page 322.
3a) Precompute_8bit
static int bits_in_char [256] ;
int bitcount (unsigned int n) {
// works only for 32-bit ints
return bits_in_char [n & 0xffu]
+ bits_in_char [(n >> 8 ) & 0xffu]
+ bits_in_char [(n >> 16) & 0xffu]
+ bits_in_char [(n >> 24) & 0xffu] ;
}
|
Precompute_8bit assumes an array bits_in_char such that bits_in_char[i] contains the number of 1 bits in the binary representation for i. It repeatedly updates count by masking out the last eight bits in n, and indexing into bits_in_char.
3b) Precompute_16bit
static char bits_in_16bits [0x1u << 16] ;
int bitcount (unsigned int n) {
// works only for 32-bit ints
return bits_in_16bits [n & 0xffffu]
+ bits_in_16bits [(n >> 16) & 0xffffu] ;
}
|
Precompute_16bit is a variant of Precompute_8bit in that an array bits_in_16bits[] stores the number of 1 bits in successive 16 bit numbers (shorts).
4) Parallel Count
#define TWO(c) (0x1u << (c))
#define MASK(c) (((unsigned int)(-1)) / (TWO(TWO(c)) + 1u))
#define COUNT(x,c) ((x) & MASK(c)) + (((x) >> (TWO(c))) & MASK(c))
int bitcount (unsigned int n) {
n = COUNT(n, 0) ;
n = COUNT(n, 1) ;
n = COUNT(n, 2) ;
n = COUNT(n, 3) ;
n = COUNT(n, 4) ;
/* n = COUNT(n, 5) ; for 64-bit integers */
return n ;
}
|
Parallel Count carries out bit counting in a parallel fashion. Consider n after the first line has finished executing. Imagine splitting n into pairs of bits. Each pair contains the number of ones in those two bit positions in the original n. After the second line has finished executing, each nibble contains the number of ones in those four bits positions in the original n. Continuing this for five iterations, the 64 bits contain the number of ones among these sixty-four bit positions in the original n. That is what we wanted to compute.
5) Nifty Parallel Count
#define MASK_01010101 (((unsigned int)(-1))/3)
#define MASK_00110011 (((unsigned int)(-1))/5)
#define MASK_00001111 (((unsigned int)(-1))/17)
int bitcount (unsigned int n) {
n = (n & MASK_01010101) + ((n >> 1) & MASK_01010101) ;
n = (n & MASK_00110011) + ((n >> 2) & MASK_00110011) ;
n = (n & MASK_00001111) + ((n >> 4) & MASK_00001111) ;
return n % 255 ;
}
|
Nifty Parallel Count works the same way as Parallel Count for the first three iterations. At the end of the third line (just before the return), each byte of n contains the number of ones in those eight bit positions in the original n. A little thought then explains why the remainder modulo 255 works.
According to Don Knuth (The Art of Computer Programming Vol IV, p 11), in the first textbook on programming, The Preparation of Programs for an Electronic Digital Computer by Wilkes, Wheeler and Gill (1957, reprinted 1984), pages 191–193 presented Nifty Parallel Count by D B Gillies and J C P Miller.
6) MIT HAKMEM Count
int bitcount(unsigned int n) {
/* works for 32-bit numbers only */
/* fix last line for 64-bit numbers */
register unsigned int tmp;
tmp = n - ((n >> 1) & 033333333333)
- ((n >> 2) & 011111111111);
return ((tmp + (tmp >> 3)) & 030707070707) % 63;
}
|
MIT HAKMEM Count is funky. Consider a 3 bit number as being 4a+2b+c. If we shift it right 1 bit, we have 2a+b. Subtracting this from the original gives 2a+b+c. If we right-shift the original 3-bit number by two bits, we get a, and so with another subtraction we have a+b+c, which is the number of bits in the original number. How is this insight employed? The first assignment statement in the routine computes tmp. Consider the octal representation of tmp. Each digit in the octal representation is simply the number of 1’s in the corresponding three bit positions in n. The last return statement sums these octal digits to produce the final answer. The key idea is to add adjacent pairs of octal digits together and then compute the remainder modulus 63. This is accomplished by right-shifting tmp by three bits, adding it to tmp itself and ANDing with a suitable mask. This yields a number in which groups of six adjacent bits (starting from the LSB) contain the number of 1’s among those six positions in n. This number modulo 63 yields the final answer. For 64-bit numbers, we would have to add triples of octal digits and use modulus 1023. This is HACKMEM 169, as used in X11 sources. Source: MIT AI Lab memo, late 1970’s.
7) Builtin Instructions
GNU compiler allows for
int __builtin_popcount (unsigned int x);
which translates into a single CPU instruction if the underlying machine architecture supports it. For example, Intel machines have POPCNT (SSE4 Instruction set announced in 2006). Many GCC builtin functions exist.
No Optimization Some Optimization Heavy Optimization
Precomp_16 52.94 Mcps Precomp_16 76.22 Mcps Precomp_16 80.58 Mcps
Precomp_8 29.74 Mcps Precomp_8 49.83 Mcps Precomp_8 51.65 Mcps
Parallel 19.30 Mcps Parallel 36.00 Mcps Parallel 38.55 Mcps
MIT 16.93 Mcps MIT 17.10 Mcps Nifty 31.82 Mcps
Nifty 12.78 Mcps Nifty 16.07 Mcps MIT 29.71 Mcps
Sparse 5.70 Mcps Sparse 15.01 Mcps Sparse 14.62 Mcps
Dense 5.30 Mcps Dense 14.11 Mcps Dense 14.56 Mcps
Iterated 3.60 Mcps Iterated 3.84 Mcps Iterated 9.24 Mcps
Mcps = Million counts per second
|
Which of the several bit counting routines is the fastest? Results of speed trials on an i686 are summarized in the table on left. “No Optimization” was compiled with plain gcc. “Some Optimizations” was gcc -O3. “Heavy Optimizations” corresponds to gcc -O3 -mcpu=i686 -march=i686 -fforce-addr -funroll-loops -frerun-cse-after-loop -frerun-loop-opt -malign-functions=4.
Thanks to Seth Robertson who suggested performing speed trials by extending bitcount.c. Seth also pointed me to MIT_Hackmem routine. Thanks to Denny Gursky who suggested the idea of Precompute_11bit. That would require three sums (11-bit, 11-bit and 10-bit precomputed counts). I then tried Precompute_16bit which turned out to be even faster.
If you have niftier solutions up your sleeves, please send me an e-mail or write comments below!
Further Reading:
- HAKMEM (bit counting is memo number 169), MIT AI Lab, Artificial Intelligence Memo No. 239, February 29, 1972.
- Bit Twiddling Hacks by Sean Anderson at Stanford University.
- Bitwise Tricks and Techniques by Don Knuth (The Art of Computer Programming, Part IV).
On 15 March 2009, this article was discussed on Reddit — you might learn quite a bit by reading the comments therein.
Written in assembly the maybe fasest version – apart from the precomputes naturally – is the “Sparse Ones”.
For unsigned long long variables:
unsigned char bitcount(unsigned long long a){
// value can’t be greater than 64 and so we can improve the performance
//by declaring the function as unsigned char
__asm {
xor eax, eax // set return to 0
mov edx, dword ptr a // set edx to the first 32 bits (0-31)
test edx, edx // compare edx to zero (get e flag)
je SHORT L2 // jump if equal
L1:
mov ebx, edx // set ebx to edx
sub edx, 1 // decrease edx
add eax, 1 // increase eax
and edx, ebx // set edx to edx & ebx (get e flag)
jne SHORT L1 // jump if not equal zero
L2:
mov edx, dword ptr a + 4 // set edx to the second 32 bits (32-63)
test edx, edx // compare edx to zero (get e flag)
je SHORT L4 // jump if equal
L3:
mov ebx, edx // set ebx to edx
sub edx, 1 // decrease edx
add eax, 1 // increase eax
and edx, ebx // set edx to edx & ebx (get e flag)
jne SHORT L3 // jump if not equal zero
L4: // end
}
}
For an unsigned int variable.
unsigned char bitcount(unsigned int a){
__asm {
xor eax, eax // set return to 0
mov edx, dword ptr a // set edx to the first 32 bits (0-31)
test edx, edx // compare edx to zero (get e flag)
je SHORT L2 // jump if equal
L1:
mov ebx, edx // set ebx to edx
sub edx, 1 // decrease edx
add eax, 1 // increase eax
and edx, ebx // set edx to edx & ebx (get e flag)
jne SHORT L1 // jump if not equal zero
L2: // end
}
}
Isn’t it a bit strange, that the nifty parallel actually performs worst than the simple parallel one ?
Also, the modulo operation, as long as it uses a power of two, can be achieved with the & (bitwise and) instruction.
y=x % 64 can be written as y=x&63
Assembly wise, the second instruction executes about instantly, but the first one does take time indeed (maybe 5 to 20 times more). Of course it’s possible that the compiler does this optimization. But anyway it’s probably worth it to get rid of the % operator.
Also i didn’t tryed any of the code but some home made nifty parallel (wich doesn’t use any % operation), but it’s certainly worth it to have a regression test to give witch would both validate each given function, but also enable to tune them in a more easy way for different architectures.
As far as x86 assembly is concerned, it’s probably worth mentioning the SSE instruction POPCNT wich count the number of bit set to 1 ….
(now you only have to get your hands on a list of processor that do support this instruction, wich may be tricky)
http://en.wikipedia.org/wiki/SSE4
For reference purpose, here is what i thought to be equivalent to the nifty parallel bit count (it’s given as c define maccro : it considers that src is 32 bits operand, and that n will hold the result. It doesn’t have been tuned for a particular architectures beside counting a 32 bits operand. There is very high chances that the implementation is correct, because i use it in some code. But i didn’t designed a particular non regression test suit for it either.)
It’s probably worth mentioning also that there are no conditional jump in this code : with intel modern processor, a conditional jump may easily take the time of 20 shifts instructions …
#define MASK_01010101 (((unsigned int)(-1))/3)
#define MASK_00110011 (((unsigned int)(-1))/5)
#define MASK_00001111 (((unsigned int)(-1))/17)
#define MASK_00001111_2 (((unsigned int)(-1))/257)
#define bitcountMacro(src,n) \
{ \
/* printf(”Source : %X\n”,src); */ \
n=src; \
n = (n & MASK_01010101) + ((n >> 1) & MASK_01010101) ; \
/*printf(”Result 1 : %X\n”,n);*/ \
n = (n & MASK_00110011) + ((n >> 2) & MASK_00110011) ; \
/*printf(”Result 2 : %X\n”,n); */ \
n = (n & MASK_00001111) + ((n >> 4) & MASK_00001111) ; \
/*printf(”Result 3 : %X\n”,n); */ \
n = (n & MASK_00001111_2) + ((n >> 8) & MASK_00001111_2) ; \
/* printf(”Result 4 : %X\n”,n);*/ \
n = (n & 65535) + ((n >> 16) & 65535) ; \
/*printf(”Result : %i\n”,n); */ \
}
If no divider hardware is at hand, the mod 255 can be eliminated easily. It is just the digit sum taken over the bytes (taken mod 255).
Note that the mod 63 ist just a digit sum mod 63 where a digit consists of 6 bits (63 is 2**6 – 1).
Therefore, the MIT algorithm will fail for 64-bit numbers, because the mask in the last line must contain at most 10 of the octal digits 7 (11*6 is greater than 62; each 3-bit packet can hold a value up to 6 at that point).
So you can fix MIT HACKMEM by
int bitcount (unsigned long long n)
{
unsigned long long tmp;
tmp = n
– ((n >> 1) & 0333333333333333333333ull)
– ((n >> 2) & 0111111111111111111111ull);
tmp += tmp >> 3;
return (tmp & 0707070707070707070700ull) % 63
+ (tmp & 7);
}
Cheers, Georg-Johann
And if I need to compute only the difference of 1-bits in two unsigned integers? Something faster than computing the number of 1-bits in the first uint and then subtracting the number of 1-bits in the second uint ??
To #4 Paul:
Simplest (and probably fastest) way is to XOR the two values then count the bits.
int nDifferentBits = BitCount(value1 ^ value2);
61 (…00111101)
14 (…00001110)
These two values have two 1-bits in common but four 1-bits are different.
61 ^ 14 = 49 (…00110011)
BitCount(49) = 4;
If you want to count the 1-bits that are in common use AND instead:
int nCommonBits = BitCount(value1 & value2);
61 & 14 = 12 (…00001100)
BitCount(12) = 2;
To #4 Paul:
Read that a bit (no pun intended) to quickly so post #5 doesn’t really apply to your question.
Notice that Sparse Ones and Parallel Count are the only correct answers to the two questions in the Puzzle (O(b) and O(log n) respectively).
Precompute and Iterated Count are O(n). Dense Ones is on average O(n). Nifty Parallel Count and HAKMEM can’t be parametrized.
On Precomp_16, masking of (n >> 16) by 0xffff isn’t necessary, since a right shift on an unsigned int is a logical shift (not an arithmetic shift). That will guarantee that zeroes are present in the upper 16 bits.
I wonder if anyone can help me on a similar problem.
I have a need to generate the next digit from a given digit, whose binary representation has the same bitcount as the given digit.
So given a number, say, 5, with binary representation 101, I need the next digit with a bitcount of 2, which in this case is 6 (110). However, if run again, I would then need the next digit with bitcount 2 which would be 9 (1001).
There is a potential for going mad in that you could easily overflow, but notification of overflow would be enough rather than actually trying to determine the next digit. For example, if asked for “next digit with bitcount 2″ after 11000000000, it would take quite a long time with a naive implementation to find the next (100000000001) and may well overflow as it adds an extra binary digit.
My current implementation is this naive: a simple loop ++’ing a variable and testing bitcount each iteration. This is, obviously, a slow way to do such a thing and I have a need to do this lots, quickly, on a slow processor.
I wonder if anyone knows of a better way?
what do you think about this solution?
void test()
{
int n, nr = 3, i = 1;
n = nr;
while (nr>1))
{
nr = ((n<<1)&(~n));
n = nr;
nr = nr | 1;
i = 1;
}
else
{
nr = n | (1<<i);
i++;
}
}
}
there are parts missing from the algorythm. let me try again:
void test()
{
int n, nr = 3, i = 1;
n = nr;
while (nr>1))
{
nr = ((n<<1)&(~n));
n = nr;
nr = nr | 1;
i = 1;
}
else
{
nr = n | (1<<i);
i++;
}
}
}
I need to count the number of bits in an int for a game I’m working on. It turns out that for my case, at least with my computer (core 2 duo with sse4), the gcc built in function is slow. Since mine is sparse, and known to always be 6 bits or fewer, I gained a significant speed boost by manually loop unrolling the sparse version you provided.
int sparse_ones_bitcount_6bit(uint64_t n){
int count = (n > 0);
if((n &= (n – 1))){ ++count;
if((n &= (n – 1))){ ++count;
if((n &= (n – 1))){ ++count;
if((n &= (n – 1))){ ++count;
if((n &= (n – 1))){ ++count;
}}}}}
return count;
}
[...] i-1; > ++n; > } > return n; > } > > > Trovate questo ed altri metodi qua http://gurmeetsingh.wordpress.com/20…ting-routines/ Ciao [...]
Note that the lookup table versions (precomp_16 and company) require a load from memory unless the tables are already in the cache. Therefore, you may find that real usage of these methods can be a lot slower than your “warm cache” benchmarks.
pre-computing all possible mask’s i was able to count bits in a 64 bit unsigned integer in around 0.000003000 seconds on my 1.8Ghz laptop.
Lee Dowling wants the snoob() function from Hacker’s Delight:
unsigned snoob(unsigned x) {
unsigned smallest, ripple, ones;
// x = xxx0 1111 0000
smallest = x & -x; // 0000 0001 0000
ripple = x + smallest; // xxx1 0000 0000
ones = x ^ ripple; // 0001 1111 0000
ones = (ones >> 2)/smallest; // 0000 0000 0111
return ripple | ones; // xxx1 0000 0111
}
compute them all ahead of time and look up in linear time if speed is crucial.
speaking of bit counting… how would you guys approach this problem: for each set bit, I want to “do” something with the index of that bit as a parameter. e.g. (101)b would foo(0), foo(3).
naive approach being something like:
uint64_t x;
int n = 0;
while (x) {
if (x & 1) foo(n);
x >>= 1;
n++;
}
bit sets are quite sparse and “clustery” if that makes a difference.
sorry that should be foo(0) and foo(2) (skipping foo(1))
Hi,
Is any one would like to help me on this.
I need to solve the same urgently…
Have you tried the method from here:
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
—
The best method for counting bits in a 32-bit integer v is the following:
v = v – ((v >> 1) & 0×55555555); // reuse input as temporary
v = (v & 0×33333333) + ((v >> 2) & 0×33333333); // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0×1010101) >> 24; // count
The best bit counting method takes only 12 operations, which is the same as the lookup-table method, but avoids the memory and potential cache misses of a table. It is a hybrid between the purely parallel method above and the earlier methods using multiplies (in the section on counting bits with 64-bit instructions), though it doesn’t use 64-bit instructions. The counts of bits set in the bytes is done in parallel, and the sum total of the bits set in the bytes is computed by multiplying by 0×1010101 and shifting right 24 bits.
—
It manages to avoid the division/modulo operations.
See also http://www.dalkescientific.com/writings/diary/archive/2008/07/03/hakmem_and_other_popcounts.html , where I benchmark implementations for popcounts of large data sizes. My test size has 16777216 bits instead of 32 bits, which of course has different performance characteristics. I implemented a couple of variations not mentioned here, and gave a few more links to other resources.
Answering Paul’s question, i.e.
the magnitude of the difference
between the number of one bits
in two numbers:
Integer>>bitCountDifference: theOther
| myself |
myself := self.
[ myself == 0 ifTrue: [^theOther bitCount].
theOther == 0 ifTrue: [^myself bitCount].
myself := myself bitAnd: myself – 1.
theOther := theOther bitAnd: theOther – 1.
] repeat
Usage:
diff := anInteger bitCountDifference: anotherInteger
Notes:
1) You’ll have to translate back into C,
or whatever your target language is.
2) Use whichever definition of #bitCount you prefer.
3) For more speed, inline the calls to #bitCount.
-Jim
To: Timo
Maybe you already knew this. If you don’t compile with -mpopcnt, gcc won’t emit the SSE4 popcnt insns and you get calls to __popcount[sd]i2, which are just table lookups.
Unfortunately though my benchmarks on an intel EMT64 (running 64-bit mode) show that the popcnt insns aren’t measurably faster than either Parallel or Nifty Parallel.
The 16 bit table lookups can be fast but for some people the 64k byte table can be a big waste of memory, particularly for small embedded systems.
[...] Hacks HAKMEM Item 169: MIT AI Memo 239, Feb. 29, 1972 Discussion of the Problem on StackOverflow Gurmeet Singh’s Weblog with C code Jesse Farmer’s Blog Magic [...]
I’ve a doubt in Precompute_8bit method.
We are using a static integer array. By default it will be initialised by 0.
Now, if we AND the passed integer value with 0xffu to determine the number of 1 bits set; suppose the number comes out to be 2 so, the bits_in_char[2] will be 0 and not the number of 1’s set. Same will the case for the next three statements.
So, we will always get 0 as the answer. This is wrong.