How can I convert bytes object to decimal or binary representation in python?

家住魔仙堡 提交于 2019-12-08 01:49:00

问题


I wanted to convert an object of type bytes to binary representation in python 3.x.

For example, I want to convert the bytes object b'\x11' to the binary representation 00010001 in binary (or 17 in decimal).

I tried this:

print(struct.unpack("h","\x11"))

But I'm getting:

error struct.error: unpack requires a bytes object of length 2

回答1:


Starting from Python 3.2, you can use int.from_bytes.

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'


来源:https://stackoverflow.com/questions/45010682/how-can-i-convert-bytes-object-to-decimal-or-binary-representation-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!