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
502 views
in Technique[技术] by (71.8m points)

Python merges 4 digit hex to 3 digit hex

I'm trying to send some bytes from Python. I'm using struct.pack to get the corresponding sending bytes. For example:

>>> struct.pack('BBBBBh', 200, 0, 56, 6, 0, 6)
'xc8x008x06x00x00x06x00'

If you take a close look, you can see that the second byte (that sould be x00) has been merged with the next byte (that should be x38).

In fact, if I try to concatenate by text:

>>> 'x00' + 'x38'
'x008'

The same thing happens.

I need to have 'x00x38'. Is this possible? Am I missing something related to formats or whatsoever?


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

1 Answer

0 votes
by (71.8m points)

If a byte is a printable character, Python will print it instead of its hexadecimal value.

0x38 (decimal 56) is the ASCII code for the character '8', therefore 'x00x38' is printed as 'x008'.

If you want to print the hexadecimal values for all bytes, you have to do it explicitly, for example:

print(['{:02x}'.format(b) for b in data])

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

...