How to write binary strings as bits directly into binary files in python

0 questions

How to write binary strings as bits directly into binary files in python

1 Method 1

# 需保存的字符串
s = "01010101010101001010111001100110110"
# 首先需要保存原字符串长度
l = len(s)
# 首先将s变成的8的整数倍长的字符串 可以直接在后面填0
if r := l % 8:
    s += "0"*(8-r)
# 将s转成bytes
b = bytes([int(s[i:i+8], 2) for i in range(0, len(s), 8)])
# bytes 可以直接写入以二进制模式打开的文件
# 例如
with open("test.bin", "wb") as f:
    f.write(b)

# 为了能够从文件中得到完全一致的二进制字符串,需保留原始长度l
# 从文件中还原
with open("test.bin", "rb") as f:
    data = f.read()
    binstr = "".join(["{:08b}".format(c) for c in data])
    binstr = binstr[:l] # 此时的binstr为原来的二进制字符串

Guess you like

Origin blog.csdn.net/qq_44856695/article/details/123343478