我有一个字节的二进制字符串表示,比如
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 中将字节的二进制字符串表示形式转换为实际的二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在python中的感兴趣区域周围绘制一个矩形How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
如何使用 OpenCV 检测和跟踪人员?How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
如何在图像的多个矩形边界框中应用阈值?How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
如何下载 Coco Dataset 的特定部分?How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
根据文本方向检测图像方向角度Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
使用 Opencv 检测图像中矩形的中心和角度Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)