base64_encode

#include <stdlib.h>
#include <string.h>

unsigned int base64_encode(
		unsigned char **dest,
		const unsigned char *src,
		unsigned int leng)
{
	static char index[64] =
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
			"abcdefghijklmnopqrstuvwxyz"
			"0123456789+/";

	unsigned int counter, extra_bytes;
	unsigned int byte0, byte1, byte2;
	unsigned char *p_dest, *p_iterator;

	counter = leng / 3;
	extra_bytes = leng % 3;

	p_dest = malloc((counter << 2) + 8);
	p_iterator = p_dest;
	*dest = p_iterator;

	while (counter--)
	{
		byte0 = *src++;
		byte1 = *src++;
		byte2 = *src++;

		*p_iterator++ = *(index + (byte0 >> 2));
		*p_iterator++ = *(index + ((byte0 << 4 | byte1 >> 4) & 0x3f));
		*p_iterator++ = *(index + ((byte1 << 2 | byte2 >> 6) & 0x3f));
		*p_iterator++ = *(index + (byte2 & 0x3f));
	}

	if (2 == extra_bytes)
	{
		byte0 = *src++;
		byte1 = *src;

		*p_iterator++ = *(index + (byte0 >> 2));
		*p_iterator++ = *(index + ((byte0 << 4 | byte1 >> 4) & 0x3f));
		*p_iterator++ = *(index + (byte1 << 2 & 0x3f));
		*p_iterator++ = '=';
	}
	else if (1 == extra_bytes)
	{
		byte0 = *src;

		*p_iterator++ = *(index + (byte0 >> 2));
		*p_iterator++ = *(index + (byte0 << 4 & 0x3f));
		*p_iterator++ = '=';
		*p_iterator++ = '=';
	}

	*p_iterator = 0;

	return p_iterator - p_dest;
}