c++ - 来自 bitset<n> 的有符号整数

标签 c++ c++11 bitset

如何将长度为 N (其中 0 < N < 64 ) 的给定位集转换为有符号整数。例如,给定:

std::bitset<13> b("1111111101100");

我想取回值 -20,而不是 8172。

我的方法:

int t = (static_cast<int>(b.to_ullong()));
if(t > pow(2, 13)/2)
    t -= pow(2, 13);

是否有更通用的方法来解决这个问题?

编辑: 位集实际上也是 std::bitset<64> N可以是通过其他方式传递的运行时已知值。

最佳答案

我们可以编写一个函数模板来为我们做这件事:

template <size_t N, class = std::enable_if_t<(N > 0 && N < 64)>
int64_t as_signed(const std::bitset<N>& b)
{
    int64_t v = b.to_ullong(); // safe since we know N < 64
    return b[N-1] ? ((1LL << N) - v) : v;
}

关于c++ - 来自 bitset<n> 的有符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849906/

相关文章:

c++ - 当我在 OpenGL 中按下一个键时无法绘制形状

c++ - 将 uint8 vector 转换为 ascii 十六进制字符串的更好方法

c++ - 如何使用带有指针 vector 的 STL 算法

c++ - unique_ptr 和前向声明 : the proper way to code a factory function

c++ - 在 C 或 C++ 中,我应该根据 NULL/nullptr 检查指针参数吗?

c++ - "if (getline(fin, str)) {}"是否符合C++11标准?

c++ - std::swap 不调用我的自定义交换实现 c++11

c++ - std::bitset 重新声明

java - 为什么 Java `BitSet` 没有 `shiftLeft` 和 `shiftRight` 函数?

Java - BitSet 为整数