分类: C/C++
2013-01-22 22:17:53
Base64 编码是把每 3 个字节转换成 4 个ascii 字符(根据字符表映射)
基本原理如下图:
行对应代码如下:
int base64Encode(unsigned char *pucSrc, int iSrcLen, unsigned char *pucDest, int *piDestLen) { int i = 0, j = 0, k = 0; unsigned char ucEncodeBase64Map[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; i = (iSrcLen + 2)/3*4; if(pucDest == NULL || *piDestLen < i) { return -1; } k = iSrcLen - iSrcLen % 3; for(i = j = 0; i < k; i += 3) { pucDest[j++] = ucEncodeBase64Map[(pucSrc[i]>>2)&0x3F] ; pucDest[j++] = ucEncodeBase64Map[((pucSrc[i]<<4) + (pucSrc[i+1]>>4))&0x3F]; pucDest[j++] = ucEncodeBase64Map[((pucSrc[i+1]<<2) + (pucSrc[i+2]>>6))&0x3F]; pucDest[j++] = ucEncodeBase64Map[pucSrc[i+2]&0x3F] ; } k = iSrcLen - k; if(1 == k) { pucDest[j++] = ucEncodeBase64Map[(pucSrc[i]>>2)&0x3F]; pucDest[j++] = ucEncodeBase64Map[(pucSrc[i]<<4)&0x3F]; pucDest[j++] = '='; pucDest[j] = '='; } else if(2 == k) { pucDest[j++] = ucEncodeBase64Map[(pucSrc[i]>>2)&0x3F]; pucDest[j++] = ucEncodeBase64Map[((pucSrc[i]<<4) + (pucSrc[i+1]>>4))&0x3F]; pucDest[j++] = ucEncodeBase64Map[(pucSrc[i+1]<<2)&0x3F]; pucDest[j] = '='; } return ++j; } int base64Decode(unsigned char *pucSrc, int iSrcLen, unsigned char *pucDest, int *piDestLen) { int i = 0, j = 0 ; unsigned char ucEncodeBase64Map[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; unsigned char ucDecodeBase64Map[256] = {0} ; for(j = iSrcLen; j > 0 && '=' == pucSrc[j - 1]; --j); i = (j/4)*3 + (j%4 + 1)/2; if(pucDest == NULL || *piDestLen < i) { return -1; } *piDestLen = i; j = sizeof(ucEncodeBase64Map); for(i = 0; i < j; ++i) ucDecodeBase64Map[ ucEncodeBase64Map[i] ] = i ; for(i = j = 0; i < iSrcLen; i += 4) { pucDest[j++] = ucDecodeBase64Map[pucSrc[i ]] << 2 | ucDecodeBase64Map[pucSrc[i + 1]] >> 4 ; pucDest[j++] = ucDecodeBase64Map[pucSrc[i + 1]] << 4 | ucDecodeBase64Map[pucSrc[i + 2]] >> 2 ; pucDest[j++] = ucDecodeBase64Map[pucSrc[i + 2]] << 6 | ucDecodeBase64Map[pucSrc[i + 3]] ; } return *piDestLen ; }