我有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
+1我喜歡這個。太糟糕了Python2.7沒有這個功能 –
@Jon那真是太神奇了。走另一條路可行嗎?例如:'int.from_bytes(b'\ xfd \ xff = \ x00','little')'並獲得'「10111111111111111011110」' – Olav
@Olav,yup - 適當格式化:'format(int.from_bytes(b' \ xfd \ xff = \ x00','little'),'023b')[:: - 1]' –