How to display a byte array as hex values

前端 未结 5 1934
清酒与你
清酒与你 2020-12-20 15:59
>>> 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\\         


        
5条回答
  •  时光说笑
    2020-12-20 16:32

    Try 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'
    

    Or if you want spaces to make it more readable:

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

    Python 3.6+, using f-strings:

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

提交回复
热议问题