Base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于2的6次方等于64,所以每6个位元为一个单元,对应某个可打印字符。三个字节有24个位元,对应于4个Base64单元,即3个字节需要用4个可打印字符来表示。它可用来作为电子邮件的传输编码。在Base64中的可打印字符包括字母A-Z、a-z、数字0-9,这样共有62个字符,此外两个可打印符号在不同的系统中而不同。一些如uuencode的其他编码方法,和之后binhex的版本使用不同的64字符集来代表6个二进制数字,但是它们不叫Base64。
Base64常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据。包括MIME的email、在XML中存储复杂数据。
1)base64的编码都是按字符串长度,以每3个8bit的字符为一组,
2)针对每组,首先获取每个字符的ASCII编码,
3)将ASCII编码转换成8bit的二进制,得到一组3*8=24bit的字节
4)再将这24bit划分为4个6bit的字节,并在每个6bit的字节前面都填两个高位0,得到4个8bit的字节
5)然后将这4个8bit的字节转换成10进制,对照Base64编码表 ,得到对应编码后的字符。
(注:1. 要求被编码字符是8bit的,所以须在ASCII编码范围内,\u0000-\u00ff,中文就不行。
2. 如果被编码字符长度不是3的倍数的时候,则都用0代替,对应的输出字符为=)
L u c y
ASCII: 76 117 99 121
8bit字节: 01001100 01110101 01100011 01111001 00000000 00000000
6bit字节: 010011 000111 010101 100011 011110 010000 000000 000000
十进制: 19 7 21 35 30 16 (异常) (异常)
对应编码: T H V j e Q = =
下面是libghttp库中base64编码的实现,非常的简洁清晰。
<span style="font-size:18px;">#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//b64对应表
const char b64_alphabet[65] = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/=" };
char *
http_base64_encode(const char *text) {
/* The tricky thing about this is doing the padding at the end,
* doing the bit manipulation requires a bit of concentration only */
char *buffer = NULL;
char *point = NULL;
int inlen = 0;
int outlen = 0;
/* check our args */
if (text == NULL)
return NULL;
/* Use 'buffer' to store the output. Work out how big it should be...
* This must be a multiple of 4 bytes */
inlen = strlen(text);
/* check our arg...avoid a pesky FPE */
if (inlen == 0) {
buffer = malloc(sizeof(char));
buffer[0] = '\0';
return buffer;
}
outlen = (inlen * 4) / 3;//得到输出长度
if ((inlen % 3) > 0) /* got to pad */
outlen += 4 - (inlen % 3);
buffer = malloc(outlen + 1); /* +1 for the \0 */
memset(buffer, 0, outlen + 1); /* initialize to zero */
/* now do the main stage of conversion, 3 bytes at a time,
* leave the trailing bytes (if there are any) for later */
for (point = buffer; inlen >= 3; inlen -= 3, text += 3) {
*(point++) = b64_alphabet[*text >> 2];
*(point++) = b64_alphabet[(*text << 4 & 0x30) | *(text + 1) >> 4];
*(point++) = b64_alphabet[(*(text + 1) << 2 & 0x3c) | *(text + 2) >> 6];
*(point++) = b64_alphabet[*(text + 2) & 0x3f];
}
/* Now deal with the trailing bytes */
if (inlen) {
/* We always have one trailing byte */
*(point++) = b64_alphabet[*text >> 2];
*(point++) = b64_alphabet[(*text << 4 & 0x30)
| (inlen == 2 ? *(text + 1) >> 4 : 0)];
*(point++) = (inlen == 1 ? '=' : b64_alphabet[*(text + 1) << 2 & 0x3c]);
*(point++) = '=';
}
*point = '\0';
return buffer;
}</span>参考:
http://zh.wikipedia.org/wiki/Base64
http://www.cnblogs.com/hongru/archive/2012/01/14/2321397.html
原文:http://blog.csdn.net/tangchenchan/article/details/45423029