2

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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Note this is a non standard function of GCC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.