将位写入二进制文件 [英] Writing bits to a binary file

查看:72
本文介绍了将位写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 23 位表示为一个字符串,我需要将此字符串作为 4 个字节写入二进制文件.最后一个字节始终为 0.以下代码有效(Python 3.3),但感觉不是很优雅(我对 Python 和编程还很陌生).你有什么让它变得更好的提示吗?似乎 for 循环可能很有用,但是如何在循环内进行切片而不会出现 IndexError?请注意,当我将位提取到一个字节中时,我反转了位顺序.

from 数组导入数组bin_array = array("B")bits = "10111111111111111011110" #示例字符串.它总是 23 位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))# 将 [253, 255, 61, 0] 写入文件

解决方案

你可以把它当作一个 int,然后创建 4 个字节如下:

<预><代码>>>>位 = "10111111111111111011110">>>int(bits[::-1], 2).to_bytes(4, '小')b'\xfd\xff=\x00'

I have 23 bits represented as a string, and I need to write this string to a binary file as 4 bytes. The last byte is always 0. The following code works (Python 3.3), but it doesn't feel very elegant (I'm rather new to Python and programming). Do you have any tips of making it better? It seems a for-loop might be useful, but how do I do the slicing within the loop without getting a IndexError? Note that that when I extract the bits into a byte, I reverse the bit-order.

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

解决方案

You can treat it as an int, then create the 4 bytes as follows:

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

这篇关于将位写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆