bitset::count() 的这个实现是如何工作的? [英] How does this implementation of bitset::count() work?

查看:50
本文介绍了bitset::count() 的这个实现是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 std::bitset::count 在 MSVC 2010 中的实现:

Here's the implementation of std::bitset::count with 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 有什么技巧?

Can someone explain to me how this is working? what's the trick with _Bitsperhex?

推荐答案

_Bitsperhex 包含十六进制数字中设置的位数,由数字索引.

_Bitsperhex contains the number of set bits in a hexadecimal digit, indexed by the digit.

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)进行 AND 运算,一次从它正在处理的值中检索一个数字,查找该数字中设置的位数,并将它们相加.

The function retrieves one digit at a time from the value it's working with by ANDing with 0xF (binary 1111), looks up the number of set bits in that digit, and sums them.

这篇关于bitset::count() 的这个实现是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆