这是我用C语言编写的Base64编解码算法,代码量很少,但功能没有缩水哦!
typedef unsigned char UCHAR;
typedef unsigned short USHORT;
typedef unsigned long ULONG;
static char base64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
ULONG Base64Encode(void *dst, void *src, ULONG len)
{
UCHAR *p1 = src;
char *p2 = dst;
ULONG i, v;
for (i = 0; i < len; i += 3)
{
switch (len - i)
{
case 1:
v = (p1[i] << 16);
*p2++ = base64_alphabet[v >> 18];
*p2++ = base64_alphabet[(v >> 12) & 63];
*p2++ = base64_alphabet[64];
*p2++ = base64_alphabet[64];
break;
case 2:
v = (p1[i] << 16) | (p1[i + 1] << 8);
*p2++ = base64_alphabet[v >> 18];
*p2++ = base64_alphabet[(v >> 12) & 63];
*p2++ = base64_alphabet[(v >> 6) & 63];
*p2++ = base64_alphabet[64];
break;
default:
v = (p1[i] << 16) | (p1[i + 1] << 8) | p1[i + 2];
*p2++ = base64_alphabet[v >> 18];
*p2++ = base64_alphabet[(v >> 12) & 63];
*p2++ = base64_alphabet[(v >> 6) & 63];
*p2++ = base64_alphabet[v & 63];
break;
}
}
*p2++ = '/0';
return p2 - (char *)dst;
}
ULONG Base64Decode(void *dst, void *src,ULONG len)
{
char *p1 = src;
UCHAR *p2 = dst;
ULONG i, v, n;
UCHAR base64_table[256];
for (i = 0; i < sizeof(base64_table); i++)
base64_table[i] = 255;
for (i = 0; i < 64; i++)
base64_table[base64_alphabet[i]] = (char)i;
for (i = 0, n = 0; i < len; i++)
{
if (base64_table[p1[i]] == 255)
break;
v = base64_table[p1[i]] | (v << 6);
n += 6;
if (n >= 8)
{
n -= 8;
*p2++ = (UCHAR)(v >> n);
}
}
return p2 - (UCHAR *)dst;
}