问题描述
我有一个二进制字符串再一个字节的presentation,如
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?
推荐答案
使用 2
阅读一个二进制值作为整数
Use the int
function with a base
of 2
to read a binary value as an integer.
n = int('01010101', 2)
Python 2中使用字符串来处理二进制数据,所以你会使用以整数转换为一个字节的字符串。
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)
3的Python处理二进制和文本不同,因此您需要使用代替。这并不一定直接等同于 CHR()
的功能,但在字节
构造可以采用列表字节值。我们把 N
一个元素数组中,并将其转换成一个字节
对象。
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:
open('out.bin', 'wb') as f:
f.write(data)
这篇关于转换二进制字符串再一个字节的presentation在Python实际二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!