Chinaunix首页 | 论坛 | 博客
  • 博客访问: 50789
  • 博文数量: 12
  • 博客积分: 456
  • 博客等级: 下士
  • 技术积分: 125
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-12 14:38
文章分类

全部博文(12)

文章存档

2011年(1)

2010年(1)

2009年(10)

我的朋友

分类:

2009-12-17 15:24:28

#include
#include
#include
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=(unsigned char*)malloc(buflen+1);
        memset(buf,0,buflen+1);
        memcpy(buf,src,n);
        for(i=0;i<3-n%3;i++)
            buf[n+i]='=';
    }
    dst=(unsigned char*)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=(int)strlen((char*)src);
    for(i=0;i    {
        p=(unsigned char*)strchr(ch64,(char)(((char*)src)[i]));
        if(!p)
            break;
        src[i]=(char*)p-ch64;
    }
    dst=(unsigned char*)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;
}
int main()
{
    char *src="user";
    //char src[]={'1','2','3',0,'a','b','*',0,'A','B','$'};
    unsigned char *dst1;
    unsigned char *dst2;
    unsigned int i;
    int srclen = strlen(src);
    for(i=0;i        printf("%c",src[i]);
    printf("\n");
    dst1=encode((unsigned char*)src, srclen); /* the second parameter must accord with the first one */
    printf("%s\n",dst1);
    dst2=decode(dst1);
    for(i=0;i        printf("%c",dst2[i]);
    free(dst1);
    free(dst2);
    printf("\n");
    return 0;
}
阅读(877) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~