[英]Best way to output a binary sequence in Python
我有一个二进制序列,例如: 10010111010101
。 我需要将 output 这个序列写入一个文件,然后再读取它,但我希望它尽可能地被压缩,最简单的方法是什么?
我试图将序列中的每8位(字节)和output 字节值放在一起,然后当我稍后阅读时,我一点一点地切割它,有没有更简单的方法? 或者一个可以轻松做到这一点的模块?
二进制数据的最佳文本编码是 base64 或 ascii85。
ASCII85
import base64
import sys
# Length of the binary string in bytes (32 bytes will let you have a 256 digit binary character stream)
# Keep it as low as possible to save space
length = 32
binary_string = input('Enter binary string : ')
integer = eval('0b'+binary_string)
data = integer.to_bytes(length, sys.byteorder, signed=False)
print(base64.a85encode(data).decode('utf-8'))
Base64
import base64
import sys
# Length of the binary string in bytes (32 bytes will let you have a 256 digit binary character stream)
# Keep it as low as possible to save space
length = 32
binary_string = input('Enter binary string : ')
integer = eval('0b'+binary_string)
data = integer.to_bytes(length, sys.byteorder, signed=False)
print(base64.b64encode(data).decode('utf-8'))
警告:通常sys.byteorder
是 little-endian,因此在尝试加载文件时可能会遇到问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.