下面是 std::bitset::count
与 MSVC 2010 的实现:
size_t count() const
{ // count number of set bits
static char _Bitsperhex[] = "\0\1\1\2\1\2\2\3\1\2\2\3\2\3\3\4";
size_t _Val = 0;
for (int _Wpos = _Words; 0 <= _Wpos; --_Wpos)
for (_Ty _Wordval = _Array[_Wpos]; _Wordval != 0; _Wordval >>= 4)
_Val += _Bitsperhex[_Wordval & 0xF];
return (_Val);
}
有人可以向我解释这是如何工作的吗? _Bitsperhex
有什么诀窍?
最佳答案
_Bitsperhex
包含十六进制数字中设置的位数,由数字索引。
digit: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
value: 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4
index: 0 1 2 3 4 5 6 7 8 9 A B C D E F
该函数通过与 0xF(二进制 1111)进行与操作,一次从它正在使用的值中检索一个数字,查找该数字中设置的位数,并对它们求和。
关于c++ - 这个 bitset::count() 的实现是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12324081/