![](/img/trans.png)
[英]How can I cast an std::bitset<N> to an std::bitset<M>?
[英]How can I increment std::bitset
如何在C ++中實現std::bitset<128>
的增量?
因為bitset是128位長,所以我不能簡單地做
std::bitset<128> set = std::bitset<128>();
set = std::bitset<128>(set.to_ulong() + 1ULL);
我將同意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
。
上面代碼的問題特別在於這一行:
set = std::bitset<128>(set.to_ulong() + 1ULL);
無符號long [ulong]在C ++中至少是32位類型,具體取決於OS +芯片組,因此在嘗試將128位變量轉換為此類型時,您創建了一個小問題(沒有實現更大的類型,即)。
一切都沒有丟失。 正如上面提到的@Oli Charlesworth,您可以使用bigint庫,而且它們很豐富。 我以前用的一個不錯的就是這里 。
對於您在上面嘗試執行的操作,您可以嘗試在大整數庫的上下文中對to_ulong()函數進行子操作,例如to_bigint(),它在bitset上運行。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.