Python 学习之常用内建模块(base64)

Base64 是一种用 64 个字符来表示任意二进制数据的方法。

原理

  • 首先,准备一个包含 64 个字符的数组:
['A', 'B', 'C', ... 'a', 'b', 'c', ... '0', '1', ... '+', '/']
  • 然后,对二进制数据进行处理,每 3 个字节一组,一共是 3 x 8 = 24 bit,划为 4 组,每组正好 6 个 bit:
    tupian
    这样我们得到4个数字作为索引,然后查表,获得相应的4个字符,就是编码后的字符串。
    如果要编码的二进制数据不是 3 的倍数,最后会剩下 1 个或 2 个字节怎么办?Base64 用 \x00 字节在末尾补足后,再在编码的末尾加上 1 个或 2 个 = 号,表示补了多少字节,解码的时候,会自动去掉。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 内建模块—base64 '

__author__ = 'Kevin Gong'

import base64

s = base64.b64encode('在Python中使用BASE 64编码'.encode('utf-8'))
print(s)
d = base64.b64decode(s).decode('utf-8')
print(d)

s = base64.urlsafe_b64encode('在Python中使用BASE 64编码'.encode('utf-8'))
print(s)
d = base64.urlsafe_b64decode(s).decode('utf-8')
print(d)

猜你喜欢

转载自blog.csdn.net/duoduo_11011/article/details/106463352