base64, base32, base16 和 base85 编码函数将8位字符转换为ASCII码的可打印字符, 这样可以让那些只支持ASCII的系统(例如SMTP)也可以传输任意二进制数据,代价是需要使用更多的比特来表示. base后面的数字表示每次编码时使用的字母长度. 除了这些函数之外,还有URL安全的变体其使用的字母与原函数会有少许变化.
-
Base64的编码函数 下面是一个编码文本的例子 #+BEGIN_SRC python :tangle base64_b64encode.py
base64_b64encode.py
import base64 import textwrap
Load this source file and strip the header.
with open("base64_b64encode.py", 'r', encoding='utf-8') as input: raw = input.read() initial_data = raw.split('#end_pymotw_header')[1]
byte_string = initial_data.encode('utf-8') encoded_data = base64.b64encode(byte_string)
num_initial = len(byte_string)
There will never be more than 2 padding bytes.
padding = 3 - (num_initial % 3)
print('{} bytes before encoding'.format(num_initial)) print('Expect {} padding bytes'.format(padding)) print('{} bytes after encoding\n'.format(len(encoded_data))) print(encoded_data) #+END_SRC
#+RESULTS: : 394 bytes before encoding : Expect 2 padding bytes : 528 bytes after encoding : : b'JylbMV0KCmJ5dGVfc3RyaW5nID0gaW5pdGlhbF9kYXRhLmVuY29kZSgndXRmLTgnKQplbmNvZGVkX2RhdGEgPSBiYXNlNjQuYjY0ZW5jb2RlKGJ5dGVfc3RyaW