• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: | 推荐给好友 上一篇 | 下一篇

base64编码解码的实现(C语言)

发布: 2007-7-01 20:40 | 作者: admin | 来源: | 查看: 131次 | 进入软件测试论坛讨论

领测软件测试网

/****************************************************************
 This is a sample routine of base64 algorithm.The goal is to
 illustrate principles,so some details may be ignored.
 Author email:zhangwu2003@163.com
*****************************************************************/
#include <stdio.h>
#include <string.h>
#include <malloc.h>

char*  ch64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

unsigned char *encode(unsigned char *src,int srclen)
{
 int n,buflen,i,j;
 int pading=0;
 unsigned char *buf;
 static unsigned char *dst; 

 buf=src;
 buflen=n=srclen;
 if(n%3!=0)  /* pad with ´=´ by using a temp buffer */
 {
  pading=1;
  buflen=n+3-n%3;
  buf=malloc(buflen+1);
  memset(buf,0,buflen+1);
  memcpy(buf,src,n);
  for(i=0;i<3-n%3;i++)
   buf[n+i]=´=´;
 }
 dst=malloc(buflen*4/3+1);
 memset(dst,0,buflen*4/3+1);
 for(i=0,j=0;i<buflen;i+=3,j+=4)
 {
  dst[j]=(buf[i]&0xFC)>>2;
  dst[j+1]=((buf[i]&0x03)<<4) + ((buf[i+1]&0xF0)>>4);
  dst[j+2]=((buf[i+1]&0x0F)<<2) + ((buf[i+2]&0xC0)>>6);
  dst[j+3]=buf[i+2]&0x3F; 
 }
 for(i=0;i<buflen*4/3;i++) /* map 6 bit value to base64 ASCII character */
  dst[i]=ch64[dst[i]];
 if(pading)
  free(buf);
 return dst;
}

unsigned char *decode(unsigned char *src)
{
 int n,i,j;
 unsigned char *p;
 static unsigned char *dst; 

 n=strlen(src);
 for(i=0;i<n;i++) /* map base64 ASCII character to 6 bit value */
 {
  p=strchr(ch64,src[i]);
  if(!p)
   break;
  src[i]=p-ch64;
 }
 dst=malloc(n*3/4+1);
 memset(dst,0,n*3/4+1);
 for(i=0,j=0;i<n;i+=4,j+=3)
 {
  dst[j]=(src[i]<<2) + ((src[i+1]&0x30)>>4);
  dst[j+1]=((src[i+1]&0x0F)<<4) + ((src[i+2]&0x3C)>>2);
  dst[j+2]=((src[i+2]&0x03)<<6) + src[i+3];
 }
 return dst;
}

void main()
{
// char *src="zhangwu张武";
 char src[]={´1´,´2´,´3´,0,´a´,´b´,´*´,0,´A´,´B´,´$´};
 unsigned char *dst1;
 unsigned char *dst2;
 unsigned int i;

 dst1=encode(src,11); /* the second parameter must accord with the first one */
 printf("%s\n",dst1);
 dst2=decode(dst1); 
 for(i=0;i<_msize(dst2);i++)
  printf("%c",dst2[i]);

 free(dst1);
 free(dst2);
}


延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:info@testage.com.cn 电话:010-51297073

软件测试 | 领测国际ISTQBISTQB官网TMMiTMMi认证国际软件测试工程师认证领测软件测试网