Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How to display a byte array as hex values

>>> struct.pack('2I',12, 30)
b'x0cx00x00x00x1ex00x00x00'    
>>> struct.pack('2I',12, 31)
b'x0cx00x00x00x1fx00x00x00'
>>> struct.pack('2I',12, 32)
b'x0cx00x00x00 x00x00x00'
                  ^in question
>>> struct.pack('2I',12, 33)
b'x0cx00x00x00!x00x00x00'
                  ^in question

I'd like all values to display as hex

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See bytes.hex():

>>> import struct
>>> struct.pack('2I',12,30).hex()   # available since Python 3.5
'0c0000001e000000'
>>> struct.pack('2I',12,30).hex(' ')  # separator available since Python 3.8
'0c 00 00 00 1e 00 00 00'
>>> struct.pack('2I',12,30).hex(' ',4) # bytes_per_sep also since Python 3.8
'0c000000 1e000000'

Older Python use binascii.hexlify:

>>> import binascii
>>> import struct
>>> binascii.hexlify(struct.pack('2I',12,30))
b'0c0000001e000000'

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 (but .hex() is available and easier).

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...