简体   繁体   中英

Best way to output a binary sequence in Python

I have a binary sequence, for example: 10010111010101 . I need to output this sequence to a file and then read it later but I want it to be compressed as much as possible, what is the easiest way to do this?

I have tried to take every 8 bits (byte) in the sequence together and output the byte value and then when I read it later, I cut it bit by bit, is there an easier way? or a module that does this readily?

The best textual encoding for binary data is either base64 or 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'))

WARNING: Typically sys.byteorder is little-endian, so you might run into problems when you try to load up the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM