-->

Bitset in C++, about continuously add

2020-04-21 06:20发布

问题:

I want to add 1 value to the bitset until it over flows, I am wondering how to do this, like:

bitset<20> foo; (foo=00000 00000 00000 00000) how can we implement this function, continuously add one

00000 00000 00000 00000 00000 > 00000 00000 00000 00000 00001 > 00000 00000 00000 00000 >00010 > 00000 00000 00000 00000 000011 until it overflows?

I am thinking about two ways;

foo.to_ulong();

how to convert unsigned long back to bitset again? C++ documentation indicates it is possible, but in the library, I can only see bitset (unsigned long val), which is creating a new bitset

2. somehow bit operations, both got stuck, help needed

回答1:

You may use the following: http://ideone.com/C8O8Qe

template <std::size_t N>
bool increase(std::bitset<N>& bs)
{
    for (std::size_t i = 0; i != bs.size(); ++i) {
        if (bs.flip(i).test(i) == true) {
            return true;
        }
    }
    return false; // overflow
}

And then to iterate on all values :

std::bitset<20> bs;

do {
    std::cout << bs << std::endl;
} while (increase(bs));


回答2:

The following code should help you:

bitset<20> b;

bool overflow = false;
while( ! overflow ){
    cout << b << endl; // prints bits in reversed order
    int ipos = b.size();
    overflow = true;
    while( overflow && --ipos >= 0 ){ 
        overflow = b[ipos];
        b[ipos] = ! b[ipos];
    }
}

tested by @Jarod42, thanks.



标签: c++ bitset