Chinaunix首页 | 论坛 | 博客
  • 博客访问: 164376
  • 博文数量: 24
  • 博客积分: 245
  • 博客等级: 二等列兵
  • 技术积分: 237
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-08 14:48
文章分类

全部博文(24)

文章存档

2013年(21)

2012年(3)

我的朋友

分类: 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 ;  
 } 

阅读(1392) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~