Base64编解码(C++版)

ZBase64.h

#include<string>
usingnamespacestd;

classZBase64
{
public:
/*编码
DataByte
[in]输入的数据长度,以字节为单位
*/
stringEncode(constunsignedchar*Data,intDataByte);
/*解码
DataByte
[in]输入的数据长度,以字节为单位
OutByte
[out]输出的数据长度,以字节为单位,请不要通过返回值计算
输出数据的长度
*/
stringDecode(constchar*Data,intDataByte,int&OutByte);
};

ZBase64.cpp

#include"stdAfx.h"
#include"ZBase64.h"

stringZBase64::Encode(constunsignedchar*Data,intDataByte)
{
//编码表
constcharEncodeTable[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//返回值
stringstrEncode;
unsignedcharTmp[4]={0};
intLineLength=0;
for(inti=0;i<(int)(DataByte/3);i++)
{
Tmp[1]=*Data++;
Tmp[2]=*Data++;
Tmp[3]=*Data++;
strEncode+=EncodeTable[Tmp[1]>>2];
strEncode+=EncodeTable[((Tmp[1]<<4)|(Tmp[2]>>4))&0x3F];
strEncode+=EncodeTable[((Tmp[2]<<2)|(Tmp[3]>>6))&0x3F];
strEncode+=EncodeTable[Tmp[3]&0x3F];
if(LineLength+=4,LineLength==76){strEncode+="\r\n";LineLength=0;}
}
//对剩余数据进行编码
intMod=DataByte%3;
if(Mod==1)
{
Tmp[1]=*Data++;
strEncode+=EncodeTable[(Tmp[1]&0xFC)>>2];
strEncode+=EncodeTable[((Tmp[1]&0x03)<<4)];
strEncode+="==";
}
elseif(Mod==2)
{
Tmp[1]=*Data++;
Tmp[2]=*Data++;
strEncode+=EncodeTable[(Tmp[1]&0xFC)>>2];
strEncode+=EncodeTable[((Tmp[1]&0x03)<<4)|((Tmp[2]&0xF0)>>4)];
strEncode+=EncodeTable[((Tmp[2]&0x0F)<<2)];
strEncode+="=";
}

returnstrEncode;
}

stringZBase64::Decode(constchar*Data,intDataByte,int&OutByte)
{
//解码表
constcharDecodeTable[]=
{
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
62,//'+'
0,0,0,
63,//'/'
52,53,54,55,56,57,58,59,60,61,//'0'-'9'
0,0,0,0,0,0,0,
0,1,2,3,4,5,6,7,8,9,10,11,12,
13,14,15,16,17,18,19,20,21,22,23,24,25,//'A'-'Z'
0,0,0,0,0,0,
26,27,28,29,30,31,32,33,34,35,36,37,38,
39,40,41,42,43,44,45,46,47,48,49,50,51,//'a'-'z'
};
//返回值
stringstrDecode;
intnValue;
inti=0;
while(i<DataByte)
{
if(*Data!='\r'&&*Data!='\n')
{
nValue=DecodeTable[*Data++]<<18;
nValue+=DecodeTable[*Data++]<<12;
strDecode+=(nValue&0x00FF0000)>>16;
OutByte++;
if(*Data!='=')
{
nValue+=DecodeTable[*Data++]<<6;
strDecode+=(nValue&0x0000FF00)>>8;
OutByte++;
if(*Data!='=')
{
nValue+=DecodeTable[*Data++];
strDecode+=nValue&0x000000FF;
OutByte++;
}
}
i+=4;
}
else//回车换行,跳过
{
Data++;
i++;
}
}
returnstrDecode;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值