How can I convert bytes object to decimal or binary representation in python?(如何在 python 中将字节对象转换为十进制或二进制表示?)
问题描述
我想在 python 3.x 中将字节类型的对象转换为二进制表示.
I wanted to convert an object of type bytes to binary representation in python 3.x.
例如,我想将字节对象 b'x11'
转换为二进制表示的二进制表示 00010001
(或十进制的 17).
For example, I want to convert the bytes object b'x11'
to the binary representation 00010001
in binary (or 17 in decimal).
我试过了:
print(struct.unpack("h","x11"))
但我得到了:
error struct.error: unpack requires a bytes object of length 2
推荐答案
从 Python 3.2 开始,您可以使用 int.from_bytes
.
Starting from Python 3.2, you can use int.from_bytes
.
第二个参数,byteorder
,指定字节串的 endianness.它可以是 'big'
或 'little'
.您还可以使用 sys.byteorder
来获取主机的本机字节顺序.
Second argument, byteorder
, specifies endianness of your bytestring. It can be either 'big'
or 'little'
. You can also use sys.byteorder
to get your host machine's native byteorder.
import sys
int.from_bytes(b'x11', byteorder=sys.byteorder) # => 17
bin(int.from_bytes(b'x11', byteorder=sys.byteorder)) # => '0b10001'
这篇关于如何在 python 中将字节对象转换为十进制或二进制表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 python 中将字节对象转换为十进制或二进制表示?
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01