python - Writing bits to a binary file -
i have 23 bits represented string, , need write string binary file 4 bytes. last byte 0. following code works (python 3.3), doesn't feel elegant (i'm rather new python , programming). have tips of making better? seems for-loop might useful, how do slicing within loop without getting indexerror? note that when extract bits byte, reverse bit-order.
from array import array bin_array = array("b") bits = "10111111111111111011110" #example string. it's 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) open("test.bnr", "wb") f: f.write(bytes(bin_array)) # writes [253, 255, 61, 0] file
you can treat int, create 4 bytes follows:
>>> bits = "10111111111111111011110" >>> int(bits[::-1], 2).to_bytes(4, 'little') b'\xfd\xff=\x00'
Comments
Post a Comment