Given a particular bitset<32>, how do I select and display the m LSB bits of the bitset? m is an integer value.
for example I have 10110111011110111101111011000100 and m = 8, the code should display 11000100.
Thanks
Given a particular bitset<32>, how do I select and display the m LSB bits of the bitset? m is an integer value.
for example I have 10110111011110111101111011000100 and m = 8, the code should display 11000100.
Thanks
There's a fairly neat way to do this that many people don't immediately find obvious.
It depends on the fact that subtracting one from a number resets the least significant bit that's currently set, and sets all the less significant bits.
So, ignoring the bitset
part for the moment, and dealing only with some integer type, we can do something like this:
unsigned x = 0b10110111011110111101111011000100;
unsigned m = 8;
unsigned mask = (1 << m) - 1;
unsigned result = x & mask;
I'll leave it to you to render the same basic idea in std::bitset
operators.
If your intent is to display a bitset without the leading zeros, well...sorry, but it doesn't support that directly, so if you do something like this:
std::bitset<15> x;
std::cout << x;
You'll always get exactly 15 characters of output, regardless of how many (or few) of those happen to be zeros. It is pretty easy to write code to skip the leading zeros on your own though (or to write the bitset
to a stringstream
, then trim off the leading zeros).