Base64是一种将二进制转为可打印字符的编码方法,主要用于邮件传输。Base64就是将64个字符(A-Z,a-z,0-9,+,/)作为基本字符集,把所有符号转换为这个字符集中的字符。为了将机内码转换为Base64编码,首先建立一个Base64码表(如下图),每次从输入流中取6bit,将此6bit作为下标查找Base64码表,输入对应字符。这样,没3字节机内码被转换为4字节的Base64编码。编码的结果出现最后不满4个字符时用 “=”填充。
Base64码表
代码如下:
#include<stdio.h> char table[64]= { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N' ,'O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u' ,'v','w','x','y','z', '0','1','2','3','4','5','6','7','8','9','+','/' }; void conv(unsigned char src[],unsigned char des[]) { des[0]=src[0]>>2; unsigned char tmp=((src[0]&0X03)<<4); des[1]=tmp|(src[1]>>4); tmp=((src[1]&0X0F)<<2); des[2]=tmp|(src[2]>>6); des[3]=src[2]&0X3F; for(int i=0;i<4;i++) { des[i]=table[des[i]]; } } void main() { FILE*fp1=fopen("in.txt","rb"); FILE*fp2=fopen("out.txt","wt"); unsigned char src[4]={0}; unsigned char des[5]={0}; int c; while((c=fread(src,sizeof(unsigned char),3,fp1))==3) { conv(src,des); fprintf(fp2,"%s",des); } if(c==1) { src[1]=src[2]=0; conv(src,des); des[2]=des[3]='='; fprintf(fp2,"%s",des); } if(c==2) { src[2]=0; conv(src,des); des[3]='='; fprintf(fp2,"%s",des); } fclose(fp1); fclose(fp2); }
原文地址:http://blog.csdn.net/u010839382/article/details/40748887