问题描述
我有一个字节的二进制字符串表示,比如
I have a binary string representation of a byte, such as
01010101
如何将其转换为真正的二进制值并将其写入二进制文件?
How can I convert it to a real binary value and write it to a binary file?
推荐答案
使用int
函数 使用 base
的 2
来读取二进制值作为整数.
Use the int
function with a base
of 2
to read a binary value as an integer.
n = int('01010101', 2)
Python 2 使用字符串来处理二进制数据,因此您可以使用 chr()
函数 将整数转换为单字节字符串.
Python 2 uses strings to handle binary data, so you would use the chr()
function to convert the integer to a one-byte string.
data = chr(n)
Python 3 处理二进制和文本的方式不同,因此您需要使用 字节类型代替.这没有直接等效于 chr()
函数,但 bytes
构造函数可以采用字节值列表.我们将 n
放在一个元素数组中,并将其转换为 bytes
对象.
Python 3 handles binary and text differently, so you need to use the bytes
type instead. This doesn't have a direct equivalent to the chr()
function, but the bytes
constructor can take a list of byte values. We put n
in a one element array and convert that to a bytes
object.
data = bytes([n])
一旦你有了你的二进制字符串,你就可以以二进制模式打开一个文件并将数据写入它,如下所示:
Once you have your binary string, you can open a file in binary mode and write the data to it like this:
with open('out.bin', 'wb') as f:
f.write(data)
这篇关于在 Python 中将字节的二进制字符串表示形式转换为实际的二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!