Edit: I am leaving the original question below, but the conversion is not as slow as I claimed. There is a bug in my original program that caused the function to be called with a much longer input than I intended. Indeed, converting from a string to a bit vector only takes about 1.5x as long as converting the other way.
I need to convert a string to vector<bool>. The conversion is very slow, however. I understand that vector<bool> is a specialization of vector. I tried using vector<char> instead, but that is just as slow.
This is my code:
std::vector<bool> frombytes(const std::string &bytes)
{
std::vector<bool> output;
for (unsigned int i = 0; i < bytes.length(); i++)
{
unsigned char byte = bytes[i];
for (unsigned int j = 0; j < 8; j++)
{
output.push_back(byte >> (7 - j) & 1);
}
}
}
I am thinking that perhaps by writing 8 bits at a time, I can make this faster. However, I can't figure out a way to do so. Any suggestions would be helpful. Thanks!
More information:
- I have tried
vector::reserve, but that did not make much difference. - I am compiling the program using g++ with the "
-O3" flag.