1

If I have a bitset like:

std::bitset<8> bs = 00000101;

how can I only retrieve the bitset "101" from bs? To make things simpler, I already know I will need the first three bits.

With @Baum's help I have something like this so far:

std::bitset<8> bs = 00000101;
int off = 3; // the number of bits I would like
std::string offStr;  // final substring of bitset I wanted
for (std::size_t i = 0; i < off; ++i)
{
      offStr += bs[i];
}
return offStr; // resulting substring
kmk09k
  • 324
  • 1
  • 5
  • 12

3 Answers3

0

It will work if you

  1. put the right value in the bitset (i.e. you want 5_10 = 101_2 but you do octal 0000101_8 = 65_10), and
  2. properly add the representation to your string.

Try the following:

std::bitset<8> bs(5);// = 00000101;
int off = 3; // the number of bits I would like
std::string offStr;  // final substring of bitset I wanted
for (std::size_t i = 0; i < off; ++i)
{
      offStr += (bs[i] ? "1" : "0");
}

Note, though, that if you are using std::string::operator+= the bits will be in the wrong order, so either change your loop, or better, pre-allocate the string and use operator[].

crazypeter
  • 1,279
  • 1
  • 10
  • 14
0

You can try the following as well:

using namespace std;   
bitset<8> bs(5);// = 00000101;
int off = 3; // the number of bits I would like   
string offStr = bs.to_string().substr(8-off,off);  // final substring of bitset I wanted  
  • Recommending the use of `using namespace std;` is very risky, here on Stack Overflow. See [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/10871073) I strongly suggest you edit/improve your code, or you are likely to attract downvotes. – Adrian Mole Feb 27 '21 at 20:15
0
#include <iostream>

unsigned int clip(unsigned int bitset, const unsigned int offset){
    static const unsigned int integer_bitsize = sizeof(unsigned int) * 8;
    if(offset >= integer_bitsize) return bitset;
    bitset <<= (integer_bitsize - offset);
    bitset >>= (integer_bitsize - offset);
    return bitset;
}

int main(int argc, char *argv[]){
    int a = clip(5, 3);
    int b = clip(13, 3);
    std::cout << a << " " << b << std::endl;
    return 0;
}

Using the shift operator works great. Just make sure to use unsigned int.

paladin
  • 765
  • 6
  • 13