本文介紹了如何在 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 中將字節對象轉換為十進制或二進制表示?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!