如何将c++位集中的位子集转换为数字?(复制)

时间:2022-04-20 02:59:27

This question already has an answer here:

这个问题已经有了答案:

I have an std::bitset and the bitset type also provides a to_ulong method to translate the bitset into a number, my problem is about translating the bitset into a number while just considering a range in that bitset, I need to implement my own powerof2 function or there is something with a more standard approach ?

我有性病:bitset和bitset类型还提供了一个to_ulong方法把bitset转化成一个数字,我的问题是关于翻译bitset成bitset只有考虑一系列数量,我需要实现自己的powerof2函数或有更多的标准方法?

2 个解决方案

#1


5  

You can drop the unnecessary bits like

您可以删除不必要的位,比如

#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 with output.

生活与输出示例。

#2


1  

You can use string as intermediate storage:

您可以使用字符串作为中间存储:

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;

Prints:

打印:

11
3

#1


5  

You can drop the unnecessary bits like

您可以删除不必要的位,比如

#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 with output.

生活与输出示例。

#2


1  

You can use string as intermediate storage:

您可以使用字符串作为中间存储:

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;

Prints:

打印:

11
3