b64
import base64
"""1. 字符串的编码与解码"""
#编码:字符串 - 字节- Base64 b64encode decode
#解码Base64 - 字节- 字符串 b64decode decode
# 编码(字符串 → Base64)
text = "Hello World"
encoded_bytes = base64.b64encode(text.encode("utf-8"))# 必须转为字节
encoded_str = encoded_bytes.decode("utf-8") # 转为字符串
print(encoded_str)# "SGVsbG8gV29ybGQ="
# 解码(Base64 → 字符串)
decoded_bytes = base64.b64decode(encoded_str)# 解码为字节
decoded_text = decoded_bytes.decode("utf-8") # 转为字符串
print(decoded_text)# "Hello World"
"""2:处理二进制数据"""
# 编码二进制数据
binary_data = b"\x00\x01\x02\x03"
encoded = base64.b64encode(binary_data).decode("utf-8")# "AAECAw=="
# 解码还原
decoded = base64.b64decode(encoded)# b"\x00\x01\x02\x03"
"""3:读取文件并编码"""
# def file_to_base64(file_path):
# with open(file_path, "rb") as file:
# binary_data = file.read()
# return base64.b64encode(binary_data).decode("utf-8")
#
# # 示例:图片转 Base64
# base64_str = file_to_base64("image.png")
"""4:Base64转文件"""
# def base64_to_file(base64_str, output_path):
# decoded_data = base64.b64decode(base64_str)
# with open(output_path, "wb") as file:
# file.write(decoded_data)
#
# # 示例:还原图片
# base64_to_file(base64_str, "output_image.png")
"""# Python → JavaScript
text = "Hello World"
encoded = base64.b64encode(text.encode("utf-8")).decode("utf-8")# "SGVsbG8gV29ybGQ="
# JS 解码:atob("SGVsbG8gV29ybGQ=") → "Hello World"
# JavaScript → Python
# JS 编码:btoa("Hello World") → "SGVsbG8gV29ybGQ="
encoded_js = "SGVsbG8gV29ybGQ="
decoded = base64.b64decode(encoded_js).decode("utf-8")# "Hello World"
"""
#
s="SGVsbG8gV29ybGQ"#base64必须是4的倍数,后面加"=”号
print(s)
s+=("="*(4-len(s)%4))
print(s)
ret=base64.b64decode(s).decode("utf-8")
print(ret)
wenben=""
encoded=base64.b64encode(wenben.encode("utf-8"))
encd_str=encoded.decode("utf-8")
decoded=base64.b64decode(encd_str)
decd_str=decoded.decode("utf-8")
print(decoded)
页:
[1]