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 中将字节的二进制字符串表示形式转换为


基础教程推荐
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01