【问题标题】:How can I convert bytes object to decimal or binary representation in python?如何在 python 中将字节对象转换为十进制或二进制表示?
【发布时间】:2020-09-23 07:28:39
【问题描述】:

我想在 python 3.x 中将字节类型的对象转换为二进制表示。

例如,我想将字节对象b'\x11' 转换为二进制表示的00010001(或十进制的17)。

我试过这个:

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

但我得到了:

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

【问题讨论】:

    标签: python python-3.x type-conversion byte bytestream


    【解决方案1】:

    从 Python 3.2 开始,您可以使用int.from_bytes

    第二个参数byteorder 指定您的字节串的endianness。它可以是'big''little'。您还可以使用sys.byteorder 来获取主机的本机字节序。

    import sys
    int.from_bytes(b'\x11', byteorder=sys.byteorder)  # => 17
    bin(int.from_bytes(b'\x11', byteorder=sys.byteorder))  # => '0b10001'
    

    【讨论】:

    • 我尝试使用此方法查找 UUID 的位表示。当我对该位字符串使用 len 函数时,结果是 127。但 UUID 是 128 位数字。你能解释一下为什么计算的长度是 127 吗?
    • 0-127 是 128 个数字
    • 如果字节有前导零,则此方法不起作用。
    【解决方案2】:

    遍历字节对象会给你 8 位整数,你可以轻松地格式化以二进制表示形式输出:

    import numpy as np
    
    >>> my_bytes = np.random.bytes(10)
    >>> my_bytes
    b'_\xd9\xe97\xed\x06\xa82\xe7\xbf'
    
    >>> type(my_bytes)
    bytes
    
    >>> my_bytes[0]
    95
    
    >>> type(my_bytes[0])
    int
    
    >>> for my_byte in my_bytes:
    >>>     print(f'{my_byte:0>8b}', end=' ')
    
    01011111 11011001 11101001 00110111 11101101 00000110 10101000 00110010 11100111 10111111
    
    

    内置了一个十六进制字符串表示的函数:

    >>> my_bytes.hex(sep=' ')
    '5f d9 e9 37 ed 06 a8 32 e7 bf'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 2014-11-07
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2015-08-05
      • 2016-08-13
      • 2020-08-06
      相关资源
      最近更新 更多