Chinaunix

标题: 这个算法怎么理解?Counting bits set [打印本页]

作者: btdm123    时间: 2011-11-22 16:08
标题: 这个算法怎么理解?Counting bits set
  1. Counting bits set, in parallel

  2. unsigned int v; // count bits set in this (32-bit value)
  3. unsigned int c; // store the total here
  4. static const int S[] = {1, 2, 4, 8, 16}; // Magic Binary Numbers
  5. static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};

  6. c = v - ((v >> 1) & B[0]);
  7. c = ((c >> S[1]) & B[1]) + (c & B[1]);
  8. c = ((c >> S[2]) + c) & B[2];
  9. c = ((c >> S[3]) + c) & B[3];
  10. c = ((c >> S[4]) + c) & B[4];

  11. The B array, expressed as binary, is:

  12. B[0] = 0x55555555 = 01010101 01010101 01010101 01010101
  13. B[1] = 0x33333333 = 00110011 00110011 00110011 00110011
  14. B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111
  15. B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111
  16. B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111

  17. We can adjust the method for larger integer sizes by continuing with the patterns for the Binary Magic Numbers, B and S. If there are k bits, then we need the arrays S and B to be ceil(lg(k)) elements long, and we must compute the same number of expressions for c as S or B are long. For a 32-bit v, 16 operations are used.

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

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

  22. 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 0x1010101 and shifting right 24 bits.



复制代码

作者: fallening    时间: 2011-11-23 01:47
本帖最后由 fallening 于 2011-11-23 01:59 编辑

二分
hacker's delight 上有写
作者: btdm123    时间: 2011-11-23 09:01
回复 2# fallening


    极品好书阿,谢谢
作者: CKFuture    时间: 2011-11-23 09:39
不懂呀




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2