【问题标题】:How to convert a range subset of bits in a C++ bitset to a number? [duplicate]如何将 C++ 位集中的位范围子集转换为数字? [复制]
【发布时间】:2013-07-25 07:42:27
【问题描述】:

我有一个 std::bitset 并且 bitset 类型还提供了一个 to_ulong 方法来将 bitset 转换为数字,我的问题是将 bitset 转换为数字,同时只考虑该 bitset 中的范围,我需要实现我自己的 powerof2 函数还是有更标准的方法?

【问题讨论】:

    标签: c++ bitset std-bitset


    【解决方案1】:

    您可以删除不必要的部分,例如

    #include <bitset>
    #include <iostream>
    
    // drop bits outside the range [R, L) == [R, L - 1]
    template<std::size_t R, std::size_t L, std::size_t N>
    std::bitset<N> project_range(std::bitset<N> b)
    {
        static_assert(R <= L && L <= N, "invalid bitrange");
        b >>= R;            // drop R rightmost bits
        b <<= (N - L + R);  // drop L-1 leftmost bits
        b >>= (N - L);      // shift back into place
        return b;
    }
    
    int main()
    {
        std::bitset<8> b2(42); // [0,0,1,0,1,0,1,0]
        std::cout << project_range<0,8>(b2).to_ulong() << "\n"; // 42 == entire bitset
        std::cout << project_range<2,5>(b2).to_ulong() << "\n"; // 8, only middle bit
    }
    

    Live example 带输出。

    【讨论】:

    • @user2485710 我在原始版本中犯了一些错误。这个已经过测试,请看现场示例。
    • 等等,对我不起作用,在这种情况下 ideone.com/RNJXNH 我的程序应该打印 15,它打印 120 因为它不会丢弃最右边的位...
    • @user2485710 bits [3, 7) as a subset of [0,32) 表示 120,如果再右移 3 位,则得到 15。如果是您想要的行为,只需将最后一条语句更改为:b &gt;&gt;= (num - l + r);
    【解决方案2】:

    你可以使用string作为中间存储:

    bitset<32> bs (string("1011"));
    cout << bs.to_ullong() << endl;
    
    // take a range - 2 last bits in this case
    string s = bs.to_string().substr(bs.size() - 2);  
    
    bitset<32> bs1 (s);
    cout << bs1.to_ullong() << endl;
    

    打印:

    11 3

    【讨论】:

    • 很高兴有选项,但我认为这会产生不必要的临时变量。我需要将我的步数缩小到一个非常小的数字。
    猜你喜欢
    • 2016-08-30
    • 2019-06-18
    • 2010-10-15
    • 1970-01-01
    • 2010-10-17
    • 2018-11-05
    • 2012-08-02
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多