How to display a byte array as hex values

前端 未结 5 2286
清酒与你
清酒与你 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:37

    In Python 3.7 bytes objects don't have an encode() method. The following code doesn't work anymore.

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

    Instead of encode(), Python 3.7 code should use the hex() method, introduced in Python 3.5.

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

提交回复
热议问题