我有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)