Select orthographic mistake with the mouse pointer and press Ctrl+Enter. Let’s make our language cleaner!
Якщо помітите помилку на цій сторінці, будь ласка, виділіть її вказівником миші та натисніть Ctrl+Enter. Зробімо наше мовлення чистішим!

2007-04-11

Base64 transformations in C++

There appeared a task to encode a binary data to base64 and then decode it back. There’re many solutions, but this one I liked very much.

#include "boost/archive/iterators/base64_from_binary.hpp"
#include "boost/archive/iterators/binary_from_base64.hpp"
#include "boost/archive/iterators/transform_width.hpp"
#include <string>
#include <iostream>

using namespace std;
using namespace boost::archive::iterators;

typedef
    base64_from_binary<
        transform_width<string::const_iterator, 6, 8>
        > base64_t;

typedef
    transform_width<
        binary_from_base64<string::const_iterator>, 8, 6
        > binary_t;

int main()
{
    string str("Hello, world!");
    cout << str << endl;
    string enc(base64_t(str.begin()), base64_t(str.end()));
    cout << enc << endl;
    string dec(binary_t(enc.begin()), binary_t(enc.end()));
    cout << dec << endl;
    return 0;
}

It’s simple enough, isn’t it? But the world is not ideal, and because of a bug decoding doesn’t work, as expected. Fortunately, the bug can be worked around with a little hack.

2 коментарі:

icon_st сказав...

I want to use this very badly, but doesn't work. It crashes on "string enc(base64_t(str.begin()), base64_t(str.end()));" this line only. It works when I use str.end()-1 instead of str.end(). I posted why on boost mailing list and got a reply that it works only for data with 3 buty boundry. Do you have any idea what theose 6 and 8 represent? I couldn't find any decent documentation.

Anatoliy Sakhnik сказав...

Don’t use this code, this piece is just internals of boost::serialization. Try to use an open source library for base64 transformation instead (there’re plenty of them around).