Base64 encoder (C++)

Base64 encoder is used to convert any binary data into “printable” character sequence so that it can be carried over textual protocols such as XML. Here is a simple function to get base64 text out of byte buffer based on RFC 2045 6.8.


    std::wstring ToBase64(unsigned char const* buffer, size_t size){
        using std::wstring;
        static wchar_t const* base64Table =
            L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        
        size_t base64Size = (size + 2 - ((size + 2) % 3)) / 3 * 4;
        wstring result(base64Size, L'=');

        unsigned char const* s = buffer;  // source pointer
        size_t di = 0;                    // destination index
        for(size_t i = 0; i < size / 3; i++){
            // input: 0000_0000 0000_0000 0000_0000
            // 
            // out1:  0000_00
            // out2:         00 0000
            // out3:                _0000 00
            // out4:                        00_0000
            
            result[di++] = base64Table[s[0] >> 2];
            result[di++] = base64Table[((s[0] << 4) | (s[1] >> 4)) & 0x3f];
            result[di++] = base64Table[((s[1] << 2) | (s[2] >> 6)) & 0x3f];
            result[di++] = base64Table[s[2] & 0x3f];
            s += 3;
        }

        size_t remainSize = size % 3;
        switch(remainSize){
        case 0:
            break;
        case 1:
            result[di++] = base64Table[s[0] >> 2];
            result[di++] = base64Table[(s[0] << 4) & 0x3f];
            break;
        case 2:
            result[di++] = base64Table[s[0] >> 2];
            result[di++] = base64Table[((s[0] << 4) | (s[1] >> 4)) & 0x3f];
            result[di++] = base64Table[(s[1] << 2) & 0x3f];
            break;
        default:
            throw std::logic_error("Should not happen.");
        }
        return result;
    }
Advertisements

About Moto

Engineer who likes coding
This entry was posted in Algorithm, C++ and tagged . Bookmark the permalink.

One Response to Base64 encoder (C++)

  1. terror says:

    Hot to use it in main {
    // ??? how
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s