1

I'm not sure how to properly explain this, but I'm looking for a way to automatically set the size or number of the bitset<size> automatically

Example

cout << bitset<8>(7) << endl;

outputs with a fixed number of bits

0000 0111

I want to automatically output with variable number of bits like outputting 111 and 11001 instead of using the fixed bits.

Basically I want to cut the 0's in front when it's not used

  • 2
    Related: http://stackoverflow.com/questions/14433626/variable-size-bitset – Caramiriel Oct 21 '16 at 19:24
  • 1
    I agree with @Caramiriel, otherwise you would need to cut them off manually, in a similar manner with [this](http://stackoverflow.com/questions/24839107/how-to-ignore-remove-leading-zeros). – gsamaras Oct 21 '16 at 19:25

2 Answers2

3

That's actually two questions in one. The first is how to trim the output a given bitset (i.e. remove the leading 0's), the second how to reduce the output to a given size.

As your interested only in the ostream output, for both it should be quite appropriate to use the bitset::to_string() conversion function, followed by an application of string::substr.

With this, for your example -- where it seems you want to retain 7 bits -- you would get:

std::cout << std::bitset<8>{}.to_string().substr(1) << std::endl;  //removes the first bit 

You can combine that with a method to find the first set bit in order to construct the trim function.

davidhigh
  • 14,652
  • 2
  • 44
  • 75
0
int main() {
    int n;
    cin >> n;
    bitset<64> n2(n);
    cout << n2.to_string().substr(64-n2._Find_first()-1) << endl;
}

std::bitset::_Find.first will find the index of the first on bit.

We convert n2 to a string, we then find the substring of the string from the index where we find the most significant bit subtracted by the total length - 1, therefore giving us the required result.

Testcase:

256
100000000
ilya1725
  • 4,496
  • 7
  • 43
  • 68