CMarkup DecodeBase64 Method

static int CMarkup::DecodeBase64(
  const MCD_STR& strBase64,
  unsigned char* pBuffer,
  int nBufferLen
  );

CMarkup Developer License

DecodeBase64 is only in CMarkup Developer.

Base64 is a way of encoding a binary value into an ASCII text value that will not interfere with markup tags (see How To Handle Binary Data). Use the EncodeBase64 method to go from binary to Base64 text and use this DecodeBase64 method to go from Base64 text to binary.

In DecodeBase64, the strBase64 argument is the Base64 string, pBuffer points to a buffer which will receive the binary data, and nBufferLen is the size in bytes of that buffer.

Retrieve binary data from a document by decoding the Base64 string that comes out of the XML document. The return value of DecodeBase64 tells you the exact length of the binary data in bytes.

nBufferLen = CMarkup::DecodeBase64( xml.GetData(), pBuffer, nBufferLen );

If there is not enough room in the buffer, DecodeBase64 returns 0. So you need to know what size to allocate the buffer.

There are two ways of deciding how big to make the buffer. One way is to overestimate based on the length of the Base64 string. The string length of Base64 is 33% higher than the binary, even more with linefeeds so you can simply use that length, or a pretty safe calculation is nBase64Len * 3 / 4 + 10.

CString strBase64 = xml.GetData();
int nBase64Len = strBase64.GetLength();
int nBufferLen = nBase64Len * 3 / 4 + 10;
unsigned char* pBuffer = new unsigned char[nBufferLen];
nBufferLen = CMarkup::DecodeBase64( strBase64, pBuffer, nBufferLen );

Another way is to call DecodeBase64 with no buffer and get the exact size needed. This means the Base64 is decoded an extra time, but it is a very fast function so this is probably not a problem.

int nBufferLen = CMarkup::DecodeBase64( strBase64, NULL, 0 );

Here is an MFC example that loads an image file, encodes and decodes it, and saves the processed copy to verify that it worked:

// EncodeBase64
CFile fileRead( "Markup60s.jpg", CFile::modeRead );
int nFileLen = fileRead.GetLength();
unsigned char* pBuffer = new unsigned char[nFileLen];
nFileLen = fileRead.Read( pBuffer, nFileLen );
fileRead.Close();
CString strBase64 = CMarkup::EncodeBase64( pBuffer, nFileLen );

// DecodeBase64
nFileLen = CMarkup::DecodeBase64( strBase64, pBuffer, nFileLen );
CFile fileWrite( "test.jpg", CFile::modeWrite | CFile::modeCreate );
fileWrite.Write( pBuffer, nFileLen );
fileWrite.Close();
delete pBuffer; // don't forget this!