我有23位表示为一个字符串,我需要将这个字符串作为4个字节写入二进制文件。最后一个字节总是0。下面的代码可以工作(Python 3.3),但感觉不太优雅(我对Python和编程还比较陌生)。你有什么让它变得更好的秘诀吗?似乎for循环可能很有用,但是如何在循环中进行切片而不获得索引器?注意,当我将位提取到一个字节中时,我会反转位的顺序。
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
^{} 模块正是为这类事情而设计的—请考虑以下情况,其中对字节的转换被分解为一些不必要的中间步骤,以便更清楚地理解它:
一种更难阅读但更短的方法是:
可以将其视为int,然后按如下方式创建4个字节:
相关问题 更多 >
编程相关推荐