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.
-
1This is a trivial coding task. If the question really is whether the standard provides a way to do this efficiently, the answer is no.Potatoswatter– Potatoswatter2017-01-04 05:24:42 +00:00Commented 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.Kahless– Kahless2017-01-04 05:26:30 +00:00Commented 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.Kahless– Kahless2017-01-04 05:27:55 +00:00Commented Jan 4, 2017 at 5:27
Add a comment
|
1 Answer
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;
}
4 Comments
Kahless
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.
Kahless
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?
Kahless
Never mind the error is gone now. I copied it wrong. Sorry. I'm still curious as to what it's doing though.
Potatoswatter
@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.)