我以前也写过,c的
[C] 纯文本查看 复制代码 //编码表
unsigned char* encodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// 对字符串进行base64编码
// str:要编码的字符串
unsigned char* base64EncodeStr(unsigned char str[])
{
// 计算需要分配的内存大小
long str_len,encode_len;
str_len = strlen(str);
// (a+b-1)/b 向上取整,
// /3*4 base64编码大小
encode_len = (str_len + 2) / 3 * 4;
// 分配内存
unsigned char* encode;
encode = (unsigned char*)malloc(sizeof(unsigned char) * encode_len);
encode[encode_len] = '\0';
// 进行编码
int i,j;
for (i = 0,j = 0; i < encode_len - 2; i += 4, j += 3) {
encode[i] = encodeTable[str[j] >> 2];
encode[i + 1] = encodeTable[(str[j] & 0x3) << 4 | str[j + 1] >> 4];
encode[i + 2] = encodeTable[(str[j+1] & 0xf) << 2 | str[j + 2] >> 6];
encode[i + 3] = encodeTable[str[j + 2] & 0x3f];
}
// 补=
if (str_len % 3 == 1) {
encode[encode_len - 2] = '=';
encode[encode_len - 1] = '=';
}
else if (str_len % 3 == 2) {
encode[encode_len - 1] = '=';
}
return encode;
} |