我有23位表示为字符串,我需要将此字符串写为4字节的二进制文件.最后一个字节始终为0.以下代码可以工作(Python 3.3),但它感觉不是很优雅(我对Python和编程很新).你有什么提示让它变得更好吗?似乎for循环可能有用,但如何在循环内进行切片而不会得到IndexError?请注意,当我将这些位提取到一个字节时,我会反转位顺序.
from array import array
bin_array = array("B")
bits = "10111111111111111011110" #Example string. It's always 23 bits
byte1 = bits[:8][::-1]
byte2 = bits[8:16][::-1]
byte3 = bits[16:][::-1]
bin_array.append(int(byte1, 2))
bin_array.append(int(byte2, 2))
bin_array.append(int(byte3, 2))
bin_array.append(0)
with open("test.bnr", "wb") as f:
f.write(bytes(bin_array))
# Writes [253, 255, 61, 0] to the file
Run Code Online (Sandbox Code Playgroud)
Jon*_*nts 16
您可以将其视为int,然后创建4个字节,如下所示:
>>> bits = "10111111111111111011110"
>>> int(bits[::-1], 2).to_bytes(4, 'little')
b'\xfd\xff=\x00'
Run Code Online (Sandbox Code Playgroud)
该struct模块正是为这种事情而设计的-考虑以下内容,其中到字节的转换已分解为一些不必要的中间步骤,以使您更清楚地了解它:
import struct
bits = "10111111111111111011110" # example string. It's always 23 bits
int_value = int(bits[::-1], base=2)
bin_array = struct.pack('i', int_value)
with open("test.bnr", "wb") as f:
f.write(bin_array)
Run Code Online (Sandbox Code Playgroud)
较难阅读但更简短的方法是:
bits = "10111111111111111011110" # example string. It's always 23 bits
with open("test.bnr", "wb") as f:
f.write(struct.pack('i', int(bits[::-1], 2)))
Run Code Online (Sandbox Code Playgroud)