如何将字节数组显示为十六进制值

时间:2013-12-27 19:23:46

标签: python

>>> struct.pack('2I',12, 30)
b'\x0c\x00\x00\x00\x1e\x00\x00\x00'    
>>> struct.pack('2I',12, 31)
b'\x0c\x00\x00\x00\x1f\x00\x00\x00'
>>> struct.pack('2I',12, 32)
b'\x0c\x00\x00\x00 \x00\x00\x00'
                  ^in question
>>> struct.pack('2I',12, 33)
b'\x0c\x00\x00\x00!\x00\x00\x00'
                  ^in question

我希望所有值都显示为十六进制

5 个答案:

答案 0 :(得分:7)

如果你想让\x到处逃脱,你必须自己重新格式化;如,

>>> import struct
>>> r = struct.pack('2I',12, 33)
>>> r
b'\x0c\x00\x00\x00!\x00\x00\x00'
>>> list(r)
[12, 0, 0, 0, 33, 0, 0, 0]
>>> print("".join("\\x%02x" % i for i in r))
\x0c\x00\x00\x00\x21\x00\x00\x00

答案 1 :(得分:6)

他的怎么样?

>>> data = struct.pack('2I',12, 30)
>>> [hex(ord(c)) for c in data]
['0xc', '0x0', '0x0', '0x0', '0x1e', '0x0', '0x0', '0x0']

表达式[item for item in sequence]是所谓的list comprehension。它基本上是一种非常紧凑的方式来编写一个简单的for循环,并从结果中创建一个列表。

ord()内置函数接受一个字符串,并将其转换为一个整数,该整数是其对应的unicode代码点(对于ASCII字符集中的字符与ASCII表中的值相同)。

对于8位字符串的chr(),对于unicode对象,unichr()则相反。

然后hex()内置函数只是将整数转换为十六进制表示。


正如@TimPeters所指出的,在Python 3中你需要丢失ord(),因为迭代一个字节对象将(已经)产生整数:

Python 3.4.0a3 (default, Nov  8 2013, 18:33:56)
>>> import struct
>>> data = struct.pack('2I',12, 30)
>>> type(data)
<class 'bytes'>
>>> type(data[1])
<class 'int'>
>>>
>>> [hex(i) for i in data]
['0xc', '0x0', '0x0', '0x0', '0x1e', '0x0', '0x0', '0x0']

答案 2 :(得分:6)

尝试binascii.hexlify

>>> import binascii
>>> import struct
>>> binascii.hexlify(struct.pack('2I',12,30))
b'0c0000001e000000'
>>> binascii.hexlify(struct.pack('2I',12,31))
b'0c0000001f000000'
>>> binascii.hexlify(struct.pack('2I',12,32))
b'0c00000020000000'
>>> binascii.hexlify(struct.pack('2I',12,33))
b'0c00000021000000'

或者如果你想让空格更具可读性:

>>> ' '.join(format(n,'02X') for n in struct.pack('2I',12,33))
'0C 00 00 00 21 00 00 00'

Python 3.6+,使用f-strings:

>>> ' '.join(f'{n:02X}' for n in struct.pack('2I',12,33))
'0C 00 00 00 21 00 00 00'

答案 3 :(得分:0)

可以选择使用encode将字节数组转换为十六进制字符串。它适用于Python 2.4中的任何Python:

Python 2.7.12 (default, Oct 10 2016, 12:50:22)
>>> import struct
>>> struct.pack('2I',12, 30).encode('hex')
'0c0000001e000000'
>>> struct.pack('2I',12, 31).encode('hex')
'0c0000001f000000'
>>> struct.pack('2I',12, 32).encode('hex')
'0c00000020000000'
>>> struct.pack('2I',12, 33).encode('hex')
'0c00000021000000'

答案 4 :(得分:0)

在Python 3.7个字节中,对象没有encode()方法。以下代码不再起作用。

import struct

hex_str = struct.pack('2I',12, 30).encode('hex')

Python 3.7代码应该使用Python 3.5中引入的hex()方法来代替encode()

import struct

# hex_str will contain the '0c0000001e000000' string.
hex_str = struct.pack('2I',12, 30).hex()