【问题标题】:python convert bytearray to numbers in listpython将字节数组转换为列表中的数字
【发布时间】:2015-04-13 19:33:36
【问题描述】:

对于以下python 代码:

pt  = bytearray.fromhex('32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34')
state = bytearray(pt)

如果我使用:

print state

它发出2Cö¨ˆZ0?11˜¢à74

那么如何恢复bytearray中的内容呢?例如,将它们放在像[] 这样的列表中。

【问题讨论】:

标签: python bytearray


【解决方案1】:

您可以使用 python 在字节数组和列表之间进行转换 内置同名函数。

>>> x=[0,1,2,3,4]      # create a list 
>>> print x
[0, 1, 2, 3, 4]
>>> y = bytearray(x)   # convert the list to a bytearray    
>>> print y
(garbled binary)               <-- prints UGLY!
>>> z = list(y)        # convert the bytearray back into a list
>>> print z
[0, 1, 2, 3, 4]        

【讨论】:

    【解决方案2】:

    索引bytearray 会产生无符号字节。

    >>> pt[0]
    50
    >>> pt[5]
    90
    

    【讨论】:

      【解决方案3】:

      您可以使用简单的字符串方法制作自己的方法:

      string = '32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34'
      number = [int(i, 16) for i in string.split()]
      

      现在你有一个你想要的转换数字列表。

      【讨论】:

        【解决方案4】:

        我正在寻找'How may you convert binary into decimal values?'的答案?并找到了这个问题,所以我想尽可能多地完成Malik Brahimi's的回答。 p>

        基本上,您可以做的是创建一个列表,然后遍历它们以创建十进制列表:

        b_list = ['0', '1', '10', '11', '100', '101'] # Note, that values of list are strings
        res = [int(n, 2) for n in b_list] # Convert from base two to base ten
        print(res)
        
        # Output:
        # User@DESKTOP-CVQ282P MINGW64 ~/desktop
        # $ python backpool.py
        # [0, 1, 2, 3, 4, 5]
        

        您可能会注意到,我们可以使用这种方式来转换具有不同基数的值:二进制、十六进制等。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-12-06
          • 2011-03-11
          • 2011-07-02
          • 1970-01-01
          • 2013-10-20
          • 2014-10-17
          • 1970-01-01
          相关资源
          最近更新 更多