// base64.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
class Base64
{
private:
BYTE Hash[256];
char *Cache;
char *Trim(char *);
public:
Base64();
char *Decode(char *);
};
Base64::Base64()
{
char i;
for(i='A';i<='Z';i++)
Hash[i]=i-'A';
for(i='a';i<='z';i++)
Hash[i]=i-'a'+26;
for(i='0';i<='9';i++)
Hash[i]=i-'0'+52;
Hash['+']=62;
Hash['/']=63;
Hash['=']=0;
Cache=NULL;
}
char *Base64::Trim(char *source)
{
char *start,*end;
start=source;
if(*(start)=='=' && *(start+1)=='?')
start=start+2;
end=source+strlen(source)-1;
if(*(end)=='=' && *(end-1)=='?')
{
*(end)=0;
*(end-1)=0;
}
if(strncmp(start,"gb2312?B?",9)==0)
{
start+=9;
}
return start;
}
char *Base64::Decode(char *source)
{
char *_source;
int ptr=0;
BYTE tmp[4];
unsigned int i;
if(Cache!=NULL)
free(Cache);
Cache=(char *)malloc(sizeof(char)*strlen(source)*2);
ZeroMemory(Cache,sizeof(char)*strlen(source)*2);
_source=(char *)malloc(sizeof(char)*strlen(source)+2);
strcpy(_source,source);
_source=this->Trim(_source);
for(i=0;i<strlen(_source);i+=4)
{
//byte 1
tmp[0]=Hash[*(_source+i)];
tmp[0]=tmp[0]<<2;
tmp[1]=Hash[*(_source+i+1)];
tmp[1]=tmp[1]>>4;
tmp[0]=tmp[0] | tmp[1];
//byte 2
tmp[1]=Hash[*(_source+i+1)];
tmp[1]=tmp[1]<<4;
tmp[2]=Hash[*(_source+i+2)];
tmp[2]=tmp[2]>>2;
tmp[1]=tmp[1] | tmp[2];
//byte 3
if(*(_source+i+2)!='=')
{
tmp[2]=Hash[*(_source+i+2)];
tmp[2]=tmp[2]<<6;
tmp[3]=Hash[*(_source+i+3)];
tmp[2]=tmp[2] | tmp[3];
}
strncpy(Cache+ptr,(const char *)tmp,3);
ptr=ptr+3;
if(*(_source+i+2)=='=')
ptr--;
if(*(_source+i+3)=='=')
ptr--;
}
return Cache;
}
//for test
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
Base64 b;
b.Decode("=?gb2312?B?tPC4tDogx+vOyr+8cGt1stnX98+1zbPR0L6/yfrQ6NKqv7zExNCp16jStQ==?=");
return 0;
}