- 论坛徽章:
- 0
|
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<string.h>
- /**********************************************
- 作者:Minuit
- 时间:2007年02月05日 星期日 20时42分33秒
- 文件名:base64.c
- 描述:C base64编码操作函数
- **********************************************/
- /*
- A B C D E F G H I J K L M N O P Q
- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
- R S T U V W X Y Z a b c d e f g h
- 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
- i j k l m n o p q r s t u v w x y
- 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
- z 0 1 2 3 4 5 6 7 8 9 + / (pad) =
- 51 52 53 54 55 56 57 58 59 60 61 62 63
- */
- static char base64_table[255];
- char *decode(const char*,char **);
- char *encode(const char*,char **);
- void base64_tableinit()
- {
- int i,j;
- bzero(base64_table,255);
- for(j=0,i='A';i<='Z';i++) /*填base64编码表*/
- base64_table[i]=j++;
- for(i='a';i<='z';i++)
- base64_table[i]=j++;
- for(i='0';i<='9';i++)
- base64_table[i]=j++;
- base64_table['+']=j++;
- base64_table['/']=j++;
- base64_table['=']=j;
- }
- char *decode(const char *cptr,char **rptr)
- {
- char *res;
- int clen,len;
- static int init=0;
- if(cptr==NULL)
- return NULL;
- len=strlen(cptr);
- if(len%4) /*编了码的字符绝对是4的倍数*/
- return NULL;
- if(!init)
- {
- init=1;
- base64_tableinit();
- }
- clen=len/4;
- if((res=malloc(len-clen))==NULL)
- return NULL;
- for(*rptr=res;clen--;)
- {
- *res=base64_table[*cptr++]<<2&0xfc; /*cptr后六位移动到最高位*/
- *res++|=base64_table[*cptr]>>4; /*跟着下个字符低两位给res低两位*/
- *res=base64_table[*cptr++]<<4&0xf0; /*填充res高四位其它清0*/
- *res++|=base64_table[*cptr]>>2&0x0f; /*字符前六位移到低六位取低四位*/
- *res=base64_table[*cptr++]<<6;
- if(*cptr!='=') /*=号乎略*/
- *res++|=base64_table[*cptr++];
- }
- return *rptr;
- }
- char *encode(const char *cptr,char **rptr)
- {
- char *res;
- int i,clen,len;
- len=strlen(cptr);
- clen=len/3;
- if(cptr==NULL||(res=malloc(clen+3*2+len))==NULL)
- return NULL;
- for(*rptr=res;clen--;)
- {
- *res++=*cptr>>2&0x3f; /*取ptr高6位放入res低6位*/
- *res=*cptr++<<4&0x30; /*移动ptr最低2位到高6位然后清0其 它位*/
- *res++|=*cptr>>4; /*取ptr高4位给res低4位*/
- *res=(*cptr++&0x0f)<<2; /*取ptr低4位移动到高6位*/
- *res++|=*cptr>>6; /*取ptr高2位给res低2位*/
- *res++=*cptr++&0x3f;
- }
- if(i=len%3) /*处理多余字符只有两种情况多一个或者两个字符*/
- {
- if(i==1) /*根据base64编码补=号*/
- {
- *res++=*cptr>>2&0x3f;
- *res++=*cptr<<4&0x30;
- *res++='=';
- *res++='=';
- }
- else
- {
- *res++=*cptr>>2&0x3f;
- *res=*cptr++<<4&0x30;
- *res++|=*cptr>>4;
- *res++=(*cptr&0x0f)<<2;
- *res++='=';
- }
- }
- *res='='; /*保证最后结位为=结束原因是因为base64里有为0的编码*/
- for(res=*rptr;*res!='=';res++)
- *res="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[*res];
- rptr[0][strlen(*rptr)-1]='\0'; /*去掉最后一个=号*/
- return *rptr;
- }
复制代码
贡献两个函数本来想写着转成perl用的但是目前还没有学xs还无法转换成perl模块
因为在很多地方都用到这个我也遇到了,所以自己也来个造轮子
http://bbs.chinaunix.net/viewthread.php?tid=895303&extra=page%3D1&page=1
不知道效率如何^_^
新修改base64表初始化工作谢谢思一克提醒
[ 本帖最后由 lovesaka 于 2007-2-5 21:24 编辑 ] |
|