2

What I want to achieve is to get base64 string from std::vector<bool>. Basing on examples of boost::archive::iterator::base64_from_binary I've created the following implementation, but is has some drawbacks:

std::string get_as_base64(const std::vector<bool> &sequence) {
    namespace bai = boost::archive::iterators;

    std::ostringstream stream;

    typedef bai::base64_from_binary<bai::transform_width<std::vector<bool>::const_iterator, 6, 1, char>> base64_encoder;
    std::copy(base64_encoder(sequence.cbegin()), base64_encoder(sequence.cend()), bai::ostream_iterator<char>(stream));

    return stream.str();
}

First thing, it requires the container to has the size as the multiple of 6 (in other case it encounters infinite loop possibly by some misimplementation). Next thing, it causes some compiler warnings to occur because of mangling bool and char types. I've just think that transform_width is not the right tool because it was designed to operate on strings...

Could you propose some better implementation?

vnd
  • 356
  • 1
  • 6
  • `requires the container to has the size as the multiple of 6` that's because base64 is a 6-bit encoding – SingerOfTheFall Sep 23 '15 at 12:28
  • I'm aware of that but I also expect from the implementation to be able pad required bits without forcing me to modify the container by myself – vnd Sep 23 '15 at 12:30
  • that's impossible, as much as you can't create 2 ASCII characters from, say, 12 bits of data. – SingerOfTheFall Sep 23 '15 at 12:32
  • The code provided here: http://stackoverflow.com/questions/7053538/how-do-i-encode-a-string-to-base64-using-only-boost shows that it is possible because a string that has a single letter, and therefore 8 bits, can be encoded using base64_from_binary. – vnd Sep 23 '15 at 12:38
  • in that case you add zeros to the _original_ string to make it's size divisible by 6, and _then_ encode it to base64, not vice-versa. – SingerOfTheFall Sep 23 '15 at 12:44
  • I really don't understand what you're complaining about, in my case I also do want the implementation to pad (with falses or 0 bits) my original binary vector to make it's size divisible by 6, and then encode it to base64. – vnd Sep 23 '15 at 12:51
  • ok, I apologize. For some reason I thought you want to pad the result, not the original vector. – SingerOfTheFall Sep 23 '15 at 12:55
  • How are you using vector? Do you "view" it as a bitset? (use one!) or do you "view" it as a container of bools? Anyways, `vector` is not a container... http://stackoverflow.com/a/16569085/85371 – sehe Sep 23 '15 at 13:58
  • Yes, I know that std::vector doesn't have a method to access internal memory storage which would solve the problem, but neither std::bitset has. I use std::vector as a ordered array of bool values, are there any performance or functional issues against using it like that? Will the use of std::bitset solve somehow the problem I've mentioned? – vnd Sep 23 '15 at 14:11

0 Answers0