pvo*_*orb 7 c++ biginteger bitset
如何std::bitset<128>在C++中实现增量?
因为bitset是128位长,所以我不能简单地做
std::bitset<128> set = std::bitset<128>();
set = std::bitset<128>(set.to_ulong() + 1ULL);
Run Code Online (Sandbox Code Playgroud)
我将同意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;
}
Run Code Online (Sandbox Code Playgroud)
这0 1 2 3为我打印。