您好我写了一个base 64编码器/解码器。我的编码器工作得很完美,所以我试着反过来做我的解码器。我得到了大部分角色,但我得到了奇怪的角色。例如,如果我解码编码的'Man is'我得到'Man i}'或编码'我喜欢吃食物'给我'我喜欢吃fo?| 4?'。我不确定这些角色来自哪里。这是我的解码器的代码。
int b64_decode(FILE *in, FILE *out)
{
do {
char outbuf [57+3];// room for null \n \r
for(int i=0; i < sizeof(outbuf);i++) //filling
outbuf[i]=0;
char inbuf [76];//ratio 3ascii/4chars
for(int i=0; i < sizeof(inbuf);i++)//filling
inbuf[i]=0;
int i1;
int i2;
int i3;
int i4;
int o1;
int o2;
int o3;
int combine;
size_t read_cnt;
read_cnt = fread(inbuf,1,sizeof(inbuf),in);
for (int i = 0; i < read_cnt; i=i+4)
{
i1=inbuf[i];
i2=inbuf[i+1];
i3=inbuf[i+2];
i4=inbuf[i+3];
for (int i =0; i < sizeof(ENCODE); i++)
{
if((int)ENCODE[i]==i1)
i1=i;
if((int)ENCODE[i]==i2)
i2=i;
if((int)ENCODE[i]==i3)
i3=i;
if((int)ENCODE[i]==i4)
i4=i;
}
i3 = i3 <<6;
i2 = i2 << 12;
i1 = i1 << 18;
combine = i1+i2+i3+i4;
o3 = (combine & 0xff);
combine = combine >> 8;
o2 = (combine & 0xff);
combine = combine >> 8;
o1 = (combine & 0xff);
outbuf[i*3/4]=(char)o1;
outbuf[i*3/4+1]=(char)o2;
outbuf[i*3/4+2]=(char)o3;
if(inbuf[i*(3/4)]=='=')
outbuf[i*(3/4)]=' ';
if(inbuf[(3/4)*i+1]=='=')
outbuf[i*(3/4)+1]=' ';
if(inbuf[(3/4)*i+2]=='=')
outbuf[(3/4)*i+2]=' ';
if(inbuf[(3/4)*i+3]=='=')
outbuf[(3/4)*i+3]=' ';
if(inbuf[i*(3/4)]=='\n')
outbuf[i*(3/4)]=' ';
if(inbuf[(3/4)*i+1]=='\n')
outbuf[i*(3/4)+1]=' ';
if(inbuf[(3/4)*i+2]=='\n')
outbuf[(3/4)*i+2]=' ';
if(inbuf[(3/4)*i+3]=='\n')
outbuf[(3/4)*i+3]=' ';
if(inbuf[i*(3/4)]=='\r')
outbuf[i*(3/4)]=' ';
if(inbuf[(3/4)*i+1]=='\r')
outbuf[i*(3/4)+1]=' ';
if(inbuf[(3/4)*i+2]=='\r')
outbuf[(3/4)*i+2]=' ';
if(inbuf[(3/4)*i+3]=='\r')
outbuf[(3/4)*i+3]=' ';
}
for(int i=0; i < sizeof(outbuf);i++)
{
if(outbuf[i]==0)
{
outbuf[i+2]='\0';
outbuf[i]='\r';
outbuf[i+1]='\n';
i=sizeof(outbuf);
}
}
printf("%s",outbuf);
} while(feof(in)==0);
return 0;
}
总结一下,我从编码器中取出4个字符,在我的数组ENCODE中找到它们的值(如此反转它)并将它们设置为等于它们的位置。然后我将它们组合成一个32位数字,取3个8位数字并打印出这3个字符。我检查了它的=,\ n,\ r \ n。感谢您的任何反馈。