Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Base64 Encoder and Boost

0.00/5 (No votes)
3 Apr 2012CPOL 33.2K  
Base64 Encoder and Boost

Well, I was looking for a Base64 library recently, and I thought, “I know, I bet it is in Boost, I have Boost, and Boost has everything.” And it turns out that it does! Kind of. But it’s a bit odd and sadly incomplete.

So let’s fix it.

To start with, I didn’t really have a clue how to plug these Boost components together, so a quick scout on the beloved StackOverflow (a Programmer’s Guide to the Galaxy) yields the following code, which I have slightly modified:

using namespace boost::archive::iterators;

typedef
  insert_linebreaks<         // insert line breaks every 76 characters
    base64_from_binary<    // convert binary values to base64 characters
      transform_width<   // retrieve 6 bit integers from a sequence of 8 bit bytes
        const unsigned char *
        ,6
        ,8
        >
      >
      ,76
    >
  base64Iterator; // compose all the above operations in to a new iterator

Disgusting, isn’t it? It also doesn’t work. It will only work when the data you use is a multiple of three, so we’ll have to pad it ourselves. Here’s the full code for that:

#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/transform_width.hpp>

namespace Base64Utilities
{
  std::string ToBase64(std::vector<unsigned char> data)
  {
    using namespace boost::archive::iterators;

    // Pad with 0 until a multiple of 3
    unsigned int paddedCharacters = 0;
    while(data.size() % 3 != 0)
    {
      paddedCharacters++;
      data.push_back(0x00);
    }

    // Crazy typedef black magic
    typedef
      insert_linebreaks<         // insert line breaks every 76 characters
        base64_from_binary<    // convert binary values to base64 characters
          transform_width<   // retrieve 6 bit integers from a sequence of 8 bit bytes
            const unsigned char *
            ,6
            ,8
            >
          >
          ,76
        >
        base64Iterator; // compose all the above operations in to a new iterator

    // Encode the buffer and create a string
    std::string encodedString(
      base64Iterator(&data[0]),
      base64Iterator(&data[0] + (data.size() - paddedCharacters)));

    // Add '=' for each padded character used
    for(unsigned int i = 0; i < paddedCharacters; i++)
    {
      encodedString.push_back('=');
    }

    return encodedString;
  }
}

It’s not that elegant but it seems to work. Can you improve on this code? Can you write the decode function? Check your answers with this excellent Online Base64 Converter.
Leave your comments below! 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)