天天看点

python怎么编程十进制转化成二进制,如何在python中将字节对象转换为十进制或二进制表示形式?...

python怎么编程十进制转化成二进制,如何在python中将字节对象转换为十进制或二进制表示形式?...

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

解决方案

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'