将位写入二进制fi

2021-06-15 00:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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
3条回答
网友
1楼 ·

^{}模块正是为这类事情而设计的—请考虑以下情况,其中对字节的转换被分解为一些不必要的中间步骤,以便更清楚地理解它:

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)

一种更难阅读但更短的方法是:

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)))
网友
2楼 ·
from array import array

bin_array = array("B")
bits = "10111111111111111011110"

bits = bits + "0" * (32 - len(bits))  # Align bits to 32, i.e. add "0" to tail
for index in range(0, 32, 8):
    byte = bits[index:index + 8][::-1]
    bin_array.append(int(byte, 2))

with open("test.bnr", "wb") as f:
    f.write(bytes(bin_array))
网友
3楼 ·

可以将其视为int,然后按如下方式创建4个字节:

>>> bits = "10111111111111111011110"
>>> int(bits[::-1], 2).to_bytes(4, 'little')
b'\xfd\xff=\x00'

相关问题