今天来把Base64解码的坑填上吧,顺带着把上次的Base64编码合并在一起。
解码的原理其实就是编码的逆过程,我这就不写了,详情请注意我的上一篇博客,哈哈我就是这么懒你来打我啊。
Talk is cheap. Show me the code !
–Linus Torvalds(linux之父)
好了废话不多说直接上代码
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
| #include<stdio.h>
#include<string.h>
/*
此程序只适用于UTF-8
*/
const char base64_map[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//base64的编码表
/*编码模块的两个函数encrypt64和base64_encrypt*/
void encrypt64(char *en_three_bits,char *en_four_bits)
{ //编码函数
union{ unsigned char a[3];unsigned int b;} en;
int i;
for(i=0;i<3;i++) //把读取的3个字节赋给联合体en
en.a[2-i]=en_three_bits[i];
for(i=0;i<4;i++)
{
en_four_bits[3-i]=base64_map[en.a[0]&63];
en.b=en.b>>6;
}
en_four_bits[4]='\0';
}
void base64_encrypt(char *en_source,char *encrypted)
{ //通过此函数来将原字符串进行分割,并进行转换
int len=strlen(en_source),i;
char en_four_bits[5];
for(i=0;i<len-2;i+=3)
{
encrypt64(&en_source[i],en_four_bits);
strcat(encrypted,en_four_bits);
}
if(len%3==1)
{
encrypt64(&en_source[len-1],en_four_bits);
en_four_bits[2]='\0';
strcat(encrypted,en_four_bits);
strcat(encrypted,"==");
}
if(len%3==2)
{
encrypt64(&en_source[len-2],en_four_bits);
en_four_bits[3]='\0';
strcat(encrypted,en_four_bits);
strcat(encrypted,"=");
}
}
/*解码模块的三个函数index64和decrypted64和base64_decrypt*/
unsigned int index64(char singel_char)
{ //求对应字符的下标
int j;
for(j=0;j<64;j++)
if(singel_char==base64_map[j])
return j;
}
void decrypted64(const char *de_four_bits,char *de_three_bits)
{ //解码主模块
union {unsigned int b;char a[4];} de; //和解码一样继续通过共用体来进行特定位的读取
int i,flag=3; //通过flag标记来去除后面的若干等号
if(de_four_bits[2]=='=')
flag=1;
else if(de_four_bits[3]=='=')
flag=2;
for(de.b=0,i=0;i<4;i++) //通过四次移位操作把四个字符的下标加起来
de.b+=index64(de_four_bits[3-i])<<(i*6);
for(i=0;i<3;i++)
de_three_bits[i]=de.a[2-i];
de_three_bits[flag]='\0';
}
void base64_decrypt(const char *de_source,char *decrypted)
{ // 分割待解码的字串
int i,len=strlen(de_source);
char de_three_bits[4];
for(i=0;i<=len-4;i +=4)
{
decrypted64(&de_source[i],de_three_bits);
strcat(decrypted,de_three_bits);
}
}
void main()
{
char b1[20]="",b2[20]="";
//s1为需要编码的字符串,s2为需要解码的字串
char s1[]="hello world !",s2[]="aGVsbG8gd29ybGQgIQ==";
base64_encrypt(s1,b1);
base64_decrypt(s2,b2);
printf("字串 \"%s\" 编码后:\n%s\n",s1,b1);
printf("字串 \"%s\" 解码后:\n%s\n",s2,b2);
//printf("%s\n",b2);
}
|
这就是所有的代码了,只依赖简单的两个c标准库, 运行的速度也是非常的快的哟。
有图有真相
我就是真相图
Base64的坑就此填完,拜了个拜咧