简体   繁体   中英

Convert std::vector<bool> to std::string

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM