The best method for counting bits in a 32-bit integer

 

B[0] = 0x55555555 = 01010101 01010101 01010101 01010101
B[1] = 0x33333333 = 00110011 00110011 00110011 00110011
B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111
B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111
B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111

 

The best method for counting bits in a 32-bit integer v is the following:

v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count


 

http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 


 

 












B[0] = 0x55555555 = 01010101 01010101 01010101 01010101





B[1] = 0x33333333 = 00110011 00110011 00110011 00110011





B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111





B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111





B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111















The best method for counting bits in a 32-bit integer v is the following:












v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary




v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp






c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count 1





 01010101  01010101  01010101  01010101




v=

00000111




v >> 1


00000011




((v >> 1) & 0x55555555) 00000000 00000000 00000000 00000001





11111111 11111111 11111111 11111111




v = v - ((v >> 1) & 0x55555555);            10000000 00000000 00000000 00000110





00110011 00110011 00110011 00110011




 (v & 0x33333333) 00000000 00000000 00000000 00000010




 ((v >> 2) & 0x33333333);


00000001








00000011 0x1010101







 00000001000000010000000100000001






00000001000000010000000100000001

c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count 00000011










































 

posted @ 2010-03-13 21:43  octoberfirst  阅读(311)  评论(0编辑  收藏  举报