【base64】手写base64源码

本文最后更新于:2022年3月1日下午1点45分

要求

尽可能手写函数,例如乘方函数等等。

C语言base64编码

源代码

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
#include <stdio.h>
#include <string.h>

int fpow(int n){
int res = 1;
for ( int i = 0; i < n; i ++) res *= 2;
return res;
}

int *dec2bin(int n){
int s[8] = {0, 0, 0, 0, 0, 0, 0, 0}, t = 1;
while( n ){
s[8 - t ++] = n % 2;
n /= 2;
}
return s;
}

int bin2dec(int s[]){
int res = 0;
for ( int i = 0; i < 8; i ++)
res += s[i] * fpow(7 - i);
return res;
}

int main(){
char t[66] = "=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", s[10000];
int ans[100000], cnt = 0;
memset(ans, 0, 100000);
fgets(s, 100000, stdin);
s[strlen(s) - 1] = '\0';
for ( int i = 0; s[i]; i ++)
for ( int j = 0; j < 8; j ++)
ans[cnt ++] = dec2bin(s[i])[j];
for ( int i = 0, tmp[6] = {0, 0, 0, 0, 0, 0}, st = 2; i < cnt ; i ++)
if ( (i + 1) % 6 == 0){
tmp[st] = ans[i], st = 2;
printf("%c", t[bin2dec(tmp) + 1]);
}else tmp[st ++] = ans[i];
if ( strlen(s) % 3 == 1){
int tmp[6] = {0, 0, ans[cnt - 2], ans[cnt - 1], 0, 0};
printf("%c==", t[bin2dec(tmp) + 1]);
}
if ( strlen(s) % 3 == 2){
int tmp[6] = {0, 0, ans[cnt - 4], ans[cnt - 3], ans[cnt - 2], ans[cnt - 1]};
printf("%c=", t[bin2dec(tmp) + 1]);
}
puts("");
return 0;
}

运行结果

image-20220301134420180

C语言base64解码

挖坑,之后再填~