如何将长度为 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/