Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Show hex value for all bytes, even when ASCII characters are present

In Python (3) at least, if a binary value has an ASCII representation, it is shown instead of the hexadecimal value. For instance, the binary value of 67 which is ASCII C is show as follows:

bytes([67]) # b'C'

Whereas for binary values without ASCII representations, they are shown in hex. I.E.

b'x0f'

Is there a way to force Python to show the binary values in their binary-hex form (if this is what it is called), even when there are ASCII representations?

Edit: By this I mean, something that starts with b'x',. This would make debugging easier when you are looking for specific bytes to be printed for instance.

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There is no specific means of requiring any particular formatting (like x) for a byte string. If you really need specific formatting, you could use something like the .hex() solution from this question, but wrap it with other code to insert the formatting you need. Another useful tool is the hex builtin function. For instance, if you want x:

>>> x = bytes([67, 128])
>>> print(''.join(r'x'+hex(letter)[2:] for letter in x))
x43x80

If you just need to be able to visually distinguish the bytes, using hex by itself may work for you (it uses 0x instead of x):

>>> print(''.join(hex(letter) for letter in x))
0x430x80

There is not a way to make this the default behavior for byte strings. Whatever you do, you're going to have to write code that specifies the display format you want; you can't make Python automatically display printable bytes as x escapes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...