How can I increase std :: bitset

How can I achieve the increment on std::bitset<128> in C ++?

Since bit-bit is 128 bits long, I can't just do

 std::bitset<128> set = std::bitset<128>(); set = std::bitset<128>(set.to_ulong() + 1ULL); 
+4
source share
2 answers

I agree with Olya and say, if you want to do "big integer" things, then you should use a large integer library.

However, if you really want to do this with std::bitset , you will need to do arithmetic yourself.

 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; } 

This prints 0 1 2 3 for me.

+4
source

The problem with the above code on this line in particular:

 set = std::bitset<128>(set.to_ulong() + 1ULL); 

Unsigned long [ulong] is at least a 32-bit type in C ++, depending on the OS + chipset, therefore, trying to drop a 128-bit variable into this type, you created a small problem (without implementing a larger type, that is).

All is not lost. As @Oli Charlesworth mentioned above, you can use the bigint library, and they are numerous. Decent, which I used earlier, here .

For what you are trying to do above, you can try to pick the to_ulong () function in the context of a large integer library, something like to_bigint (), which works with bitrate.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1482836/


All Articles