Encoding in Base64 (C Source Code)

E

Base64 encoding schemes are generally used when there is a need to encode binary information that needs to be stored and transferred over media that are developed to deal with textual information. This guarantees that the data stays unchanged without modification during transfer. Base64 is generally used in a number of applications including electronic mail via MIME, and keeping complex information in XML.

The specific set of characters chosen for the 64 characters needed for the base can vary among implementations. The common concept is to select a set of 64 characters that is both part of a subset typical to most encodings. This mixture leaves the data impossible to be altered in transportation thru information systems, such as electronic mail, that were typically not 8-bit clean. The Base64 implementation in MIME uses a-z, A-Z and 0-9 for the first 62 values. Other Base64 variations share the same property but they use different symbols in the last two values.

In this post you can find a simple Base64 Encoding function

size_t base64_encode(uint8_t* result,size_t result_sz,uint8_t* data, uint8_t data_sz)
{
   size_t actual_sz = 0;
   uint8_t base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	
   memset(result, 0, result_sz);

   for (int i = 0; i < data_sz; i += 3)
   {
      result[actual_sz++] = base64_table[(data[i] & 0xFC) >> 2];
      switch (data_sz-i)
      {
         case 1:
	    result[actual_sz++] = base64_table[((data[i] & 0x03) << 4)];
	    result[actual_sz++] = '=';
	    result[actual_sz++] = '=';
	    break;
	 case 2:	
	    result[actual_sz++] = base64_table[((data[i] & 0x03) << 4) | ((data[i + 1] & 0xF0) >> 4)];
	    result[actual_sz++] = base64_table[((data[i+1] & 0x0F) << 2)];
	    result[actual_sz++] = '=';
	    break;
	 case 3:
	 default:
	    result[actual_sz++] = base64_table[((data[i] & 0x03) << 4) | ((data[i + 1] & 0xF0) >> 4)];
	    result[actual_sz++] = base64_table[((data[i + 1] & 0x0F) << 2) | ((data[i + 2] & 0xC0) >> 6)];
	    result[actual_sz++] = base64_table[((data[i + 2] & 0x3F))];
	    break;
      }
   }
   return actual_sz;
}

Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags