自己实现一个小巧的base64编码解码


int Base64Encode(BYTE* input_data, DWORD cbData, TCHAR* OUT buffer)
{
	if(!input_data || !cbData || !buffer)
		return 0;

	static char* table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	DWORD group_count = cbData / 3;
	DWORD remain_count = cbData - group_count * 3;
	DWORD dwTemp = 0;
	BYTE* pStore = (BYTE*)(&dwTemp);
	int r = 0;
	int w = 0;

	for(DWORD i = 0; i < group_count; i++)
	{
		pStore[2] = input_data[r++];
		pStore[1] = input_data[r++];
		pStore[0] = input_data[r++];

		for(int j = 0; j < 4; j++)
		{
			dwTemp <<= 6;
			buffer[w++] = table[pStore[3] & 0x3F];
		}
	}

	if(remain_count)
	{
		int k = 2;

		for(DWORD i = 0; i < remain_count; i++)
			pStore[k--] = input_data[r++];

		int rcnt = remain_count == 1 ? 2 : 3;
		int pcnt = 4 - rcnt;

		for(int j = 0; j < rcnt; j++)
		{
			dwTemp <<= 6;
			buffer[w++] = table[pStore[3] & 0x3F];
		}

		for(int j = 0; j < pcnt; j++)
			buffer[w++] = _T('=');
	}

	buffer[w] = 0;
	return w;
}

int Base64Decode(TCHAR* pBase64, DWORD cchChar, BYTE* pBuffer)
{
	if(cchChar < 4 || !pBase64 || !pBuffer)
		return 0;

	static BYTE rtable[256] =
	{
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
		52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
		10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27,
		28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64
	};
	int group_cnt = cchChar / 4 - 1;
	DWORD dwTemp = 0;
	BYTE* pStore = (BYTE*)(&dwTemp);
	int r = 0;
	int w = 0;

	for(int i = 0; i < group_cnt; i++)
	{
		dwTemp = 0;

		for(int j = 0; j < 4; j++)
		{
			dwTemp <<= 6;
			BYTE ch = rtable[ pBase64[r++] ];

			if(ch > 63)
				return -1;

			dwTemp |= ch ;
		}

		pBuffer[w++] = pStore[2];
		pBuffer[w++] = pStore[1];
		pBuffer[w++] = pStore[0];
	}

	int cc = 3;

	if(pBase64[cchChar - 1] == '=')
		cc--;

	if(pBase64[cchChar - 2] == '=')
		cc--;

	dwTemp = 0;

	for(int j = 0; j < 4; j++)
	{
		dwTemp <<= 6;
		dwTemp |= (rtable[ pBase64[r++]] & 0x3F);
	}

	int k = 2;

	for(int j = 0; j < cc; j++)
		pBuffer[w++] = pStore[k--];

	return w;
}




猜你喜欢

转载自blog.csdn.net/lif12345/article/details/60870253