-1

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

  • [Here's a documentation of the API](http://en.cppreference.com/w/cpp/utility/bitset). I'm sure you can figure it out. – StoryTeller - Unslander Monica Dec 21 '17 at 05:29
  • I tried shifting it and I was able to display 0000000000000000000000011000100. I'm trying to get rid of the 0s. I understand it's a juvenile question, but i'm just figuring out how to code. – Pavan Swarup Dec 21 '17 at 05:44

1 Answers1

4

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).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111