2

I have a vector of binary data and would like to convert this into a string. How can I go about this task. Just to be clear I and not looking to have a string of just 1's and 0's. I want it so that every 8 entries equal one char.

3
  • 1
    This is a trivial coding task. If the question really is whether the standard provides a way to do this efficiently, the answer is no. Commented Jan 4, 2017 at 5:24
  • I'm new to c++ and this doesn't seem trivial to me. I've searched extensively and cant find anything on converting vector<bool> to a string. Commented Jan 4, 2017 at 5:26
  • I saw that bitset had a to_string method but that doesn't do what I'm looking for and I wont know the size at run time so it's not an option anyway. Commented Jan 4, 2017 at 5:27

1 Answer 1

3

Iterate over the bits and use the bitwise operators to place them into char values.

There's nothing particularly tricky about this. If you're unfamiliar with bitwise arithmetic, you might try implementing it first in a more familiar language and then translate it to C++ as an exercise.

std::size_t divide_rounding_up( std::size_t dividend, std::size_t divisor )
    { return ( dividend + divisor - 1 ) / divisor; }

std::string to_string( std::vector< bool > const & bitvector ) {
    std::string ret( divide_rounding_up( bitvector.size(), 8 ), 0 );
    auto out = ret.begin();
    int shift = 0;

    for ( bool bit : bitvector ) {
        * out |= bit << shift;

        if ( ++ shift == 8 ) {
            ++ out;
            shift = 0;
        }
    }
    return ret;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey thanks. I'm not very familiar with bitwise. I haven't had much experience with binary data yet. I'll be sure to read up on it.
The following line is giving me a bit of trouble. std::string ret( divide_rounding_up( bitvector.size(), 8 ), 0 );. I'm getting the error invalid conversion from std::size_t to const char*. Also what is that line doing? I can see that it's calling the other function which returns a number. Is this presetting the size of the string?
Never mind the error is gone now. I copied it wrong. Sorry. I'm still curious as to what it's doing though.
@Kahless It's initializing a std::string to have ceil(bitvector.size()/8) characters all initialized to zero. (It might be more clear to say '\0' instead of 0.)

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.