2025年c语言b64编码,base64编码解码的实现(C语言)

c语言b64编码,base64编码解码的实现(C语言)This is a sample routine of base64 algorithm The goal is to illustrate principles so some details may be ignored Author

大家好,我是讯享网,很高兴认识大家。

/

This is a sample routine of base64 algorithm.The goal is to

illustrate principles,so some details may be ignored.

Author email:

*/

#include

#include

#include

char*  ch64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0+/";

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

{

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

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

{

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

{

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>

printf("%c",dst2[i]);

free(dst1); free(dst2);}

小讯
上一篇 2025-02-19 13:15
下一篇 2025-02-20 14:42

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/92095.html