如何在C++中实现std::bitset<128>的增量?
因为位集是128位长的,所以我不能简单地
std::bitset<128> set = std::bitset<128>();
set = std::bitset<128>(set.to_ulong() + 1ULL);发布于 2013-05-27 01:01:02
我同意Oli的观点,如果你想做“大整数”的事情,那么你应该使用大整数库。
然而,如果你真的想使用std::bitset来做这件事,你需要自己做算术运算。
template <size_t N>
std::bitset<N> increment ( std::bitset<N> in ) {
// add 1 to each value, and if it was 1 already, carry the 1 to the next.
for ( size_t i = 0; i < N; ++i ) {
if ( in[i] == 0 ) { // There will be no carry
in[i] = 1;
break;
}
in[i] = 0; // This entry was 1; set to zero and carry the 1
}
return in;
}
int main () {
std::bitset<32> foo;
std::cout << foo.to_ulong () << ' ';
foo = increment ( foo );
std::cout << foo.to_ulong () << ' ';
foo = increment ( foo );
std::cout << foo.to_ulong () << ' ';
foo = increment ( foo );
std::cout << foo.to_ulong () << std::endl;
return 0;
}这将为我打印0 1 2 3。
发布于 2013-05-27 01:04:01
上面代码的问题尤其在下面这一行中:
set = std::bitset<128>(set.to_ulong() + 1ULL);Unsigned long ulong在C++中至少是32位类型,这取决于OS +芯片组,所以在尝试将128位变量转换为this类型时,您遇到了一个小问题(即没有实现更大的类型)。
并不是一切都失败了。正如@Oli Charlesworth上面提到的,你可以使用bigint库,它们非常丰富。我以前用过的一个不错的方法是here。
对于上面要做的事情,您可以尝试在一个大整型库的上下文中继承to_ulong()函数,比如在位集上操作的to_bigint()函数。
希望这能有所帮助。
https://stackoverflow.com/questions/16761472
复制相似问题