mbed.org implementation of the abstract SmartREST library for the Cumulocity Platform SmartREST protocol.

Dependents:   MbedSmartRestMain MbedSmartRestMain

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers b64.cpp Source File

b64.cpp

00001 // Simple Base64 code
00002 // (c) Copyright 2010 MCQN Ltd.
00003 // Released under Apache License, version 2.0
00004 
00005 #include "b64.h"
00006 
00007 /* Simple test program
00008 #include <stdio.h>
00009 void main()
00010 {
00011     char* in = "amcewen";
00012     char out[22];
00013 
00014     b64_encode(in, 15, out, 22);
00015     out[21] = '\0';
00016 
00017     printf(out);
00018 }
00019 */
00020 
00021 int b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen)
00022 {
00023     // Work out if we've got enough space to encode the input
00024     // Every 6 bits of input becomes a byte of output
00025     if (aOutputLen < (aInputLen*8)/6)
00026     {
00027         // FIXME Should we return an error here, or just the length
00028         return (aInputLen*8)/6;
00029     }
00030 
00031     // If we get here we've got enough space to do the encoding
00032 
00033     const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
00034     if (aInputLen == 3)
00035     {
00036         aOutput[0] = b64_dictionary[aInput[0] >> 2];
00037         aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)];
00038         aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)];
00039         aOutput[3] = b64_dictionary[aInput[2]&0x3F];
00040     }
00041     else if (aInputLen == 2)
00042     {
00043         aOutput[0] = b64_dictionary[aInput[0] >> 2];
00044         aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)];
00045         aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2];
00046         aOutput[3] = '=';
00047     }
00048     else if (aInputLen == 1)
00049     {
00050         aOutput[0] = b64_dictionary[aInput[0] >> 2];
00051         aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4];
00052         aOutput[2] = '=';
00053         aOutput[3] = '=';
00054     }
00055     else
00056     {
00057         // Break the input into 3-byte chunks and process each of them
00058         int i;
00059         for (i = 0; i < aInputLen/3; i++)
00060         {
00061             b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4);
00062         }
00063         if (aInputLen % 3 > 0)
00064         {
00065             // It doesn't fit neatly into a 3-byte chunk, so process what's left
00066             b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4));
00067         }
00068     }
00069 }
00070