There is no .lsb()
or .msb()
member functions, but std::bitset
does provide .size()
and .test()
(and .any()
, credit to @phuctv for use of .any()
over .count()
) with which you can construct the lsb and msb routines.
Presuming a valid std::bitset
you can verify that at least one bit is set true using .any()
(or just check the unsigned value). After verifying at least one bit is true, simply loop from bit-0
to bit-(bitset.size() - 1)
checking for a set bit with .test()
to obtain the LSB. Then just loop in reverse with the same test to find the MSB.
A short implementation would be:
#include <iostream>
#include <bitset>
int main () {
size_t i = 0; /* bit indiex */
std::bitset<8> bits (236); /* bitset '11101100' */
if (!bits.any()) { /* validate at least 1 bit set */
std::cerr << "pop count is zero.\n";
return 1;
}
/* loop bit 0 to bits.size() - 1 for LSB */
do {
if (bits.test(i)) /* test if bit set */
break;
} while (++i < bits.size());
std::cout << "lsb in '" << bits << "' is: " << i << '\n';
/* loop bit bits.size() - 1 to 0 for MSB */
i = bits.size();
while (i--) {
if (bits.test(i)) /* test if bit set */
break;
}
std::cout << "msb in '" << bits << "' is: " << i << '\n';
}
Example Use/Output
$ ./bin//bitset_test
lsb in '11101100' is: 2
msb in '11101100' is: 7
Extend std::bitset and Add .lsb()
and .msb()
Member Functions
In addition to simply writing a couple of functions, you can just derive from std::bitset
and add .lsb()
and .msb()
member functions to the derived class.
A short class declaration using the same implementations above could be:
template<size_t Nb>
class mybitset : public std::bitset<Nb> {
std::bitset<Nb> bits;
public:
mybitset (const std::bitset<Nb>&b) : std::bitset<Nb>{b} { bits = b; }
size_t lsb(); /* extend std::bitset with .lsb() and .msb() members */
size_t msb();
template<size_t NB>
friend std::ostream& operator << (std::ostream& os, const mybitset<NB>& b);
};
Then you can simply use the .lsb()
and .msb()
members directly, e.g.
int main () {
mybitset<8> bits (236); /* derived class */
if (!bits.any()) { /* validate at least one bit set */
std::cerr << "bitset value is zero -- zero pop count.\n";
return 1;
}
/* output LSB and MSB */
std::cout << "lsb in '" << bits << "' is: " << bits.lsb() <<
"\nmsb in '" << bits << "' is: " << bits.msb() << '\n';
}
(same output)