Convert binary string representation of a byte to actual binary value in Python(在 Python 中将字节的二进制字符串表示形式转换为实际的二进制值)
问题描述
我有一个字节的二进制字符串表示,比如
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 中将字节的二进制字符串表示形式转换为实际的二进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中将字节的二进制字符串表示形式转换为
基础教程推荐
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
