Problem I: base64编码

发布时间 2023-04-24 19:19:56作者: hangsingplus

Problem Description

对于任意二进制文件(如图像、声音、视频、程序等),都可以用base64编码。
base64编码方法:先把二进制代码划分为一系列24位长的单元,然后把每一个24位单元划分为4个6位的组。每一个6位组按下列方法转换为ASCII码。6位二进制有64个不同的值,0-63。用A表示0,B表示1,等。26个大写字母排列完毕后,再用26个小写字母,然后再用10个数字,最后用+表示62,用/表示63。当要编码的个数不是3的倍数时,等号符“=”被用作填充符。
例如:
24位二进制代码:01001001 00110001 01111001
划分为4个6位组:010010 010011 000101 111001
对应的base64编码:  S          T          F          5
对应的base64编码的二进制代码:01010011 01010100 01000110 00110101

Input Description

输入一篇文本。长度不超过10000个字符。

Output Description

输出编码后的文本。

Sample Input

#include <stdio.h>
int main()
{
    int a,b;
    scanf("%d %d",&a, &b);
    printf("%d\n",a+b);
    return 0;
}

Sample Output

I2luY2x1ZGUgPHN0ZGlvLmg+CmludCBtYWluKCkKewogICAgaW50IGEsYjsKICAgIHNjYW5mKCIlZCAlZCIsJmEsICZiKTsKICAgIHByaW50ZigiJWRcbiIsYStiKTsKICAgIHJldHVybiAw

 1 def read_in():
 2     list = []
 3     while True:
 4         try:
 5             line = input()
 6         except EOFError:
 7             break
 8         list.append(line)
 9         list.append("\n")
10 
11     src = "".join(list)
12     return src
13 
14 
15 def base_64(src):
16     keystr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
17 
18     src = list(src)
19     length = len(src)
20     if length % 3 != 0:
21         if length % 3 == 1:
22             src.append("=")
23             src.append("=")
24             length += 2
25         else:
26             src.append("=")
27             length += 1
28 
29     src = list(map(ord, src))
30     i = 0
31     dst = []
32     while i < length:
33         ch1 = src[i]
34         i += 1
35         ch2 = src[i]
36         i += 1
37         ch3 = src[i]
38         i += 1
39 
40         ench1 = ch1 >> 2
41         ench2 = ((ch1 & 3) << 4) | (ch2 >> 4)
42         ench3 = ((ch2 & 15) << 2) | (ch3 >> 6)
43         ench4 = ch3 & 63
44 
45         dst.append(keystr[ench1])
46         dst.append(keystr[ench2])
47         dst.append(keystr[ench3])
48         dst.append(keystr[ench4])
49 
50     dst = "".join(dst)
51     return dst
52 
53 
54 if __name__ == "__main__":
55     str = read_in()
56     ans = base_64(str)
57     print(ans)