6

I did

>>> b0 = open('file','rb')

Then

>>> b0.read(10)

gives

b'\xb8\xaaK\x1e^J)\xab_I'

How can I get things printed all as pure hex bytes? I want

b'\xb8\xaa\x4b\x1e\x5e\x4a\x29\xab\x5f\x49'

(PS: is it possible to print it pretty? like

B8 AA 4B 1E 5E 4A 29 AB 5F 49

or colon separated.)

2
  • 2
    string.encode('hex')? :) Commented Apr 12, 2013 at 6:50
  • 4
    @Allendar - no, in pyhon3 that doesn't work. binascii.hexlify Commented Apr 12, 2013 at 6:53

1 Answer 1

6
>>> s = b'\xb8\xaaK\x1e^J)\xab_I'
>>> ' '.join('{:02X}'.format(c) for c in s)
'B8 AA 4B 1E 5E 4A 29 AB 5F 49'

or, slightly more concisely:

>>> ' '.join(map('{:02X}'.format, s))
'B8 AA 4B 1E 5E 4A 29 AB 5F 49'
Sign up to request clarification or add additional context in comments.

2 Comments

I found this in another answer. It's kind of indirect. Is there a way to set some environment variable so that bytes are printed as is?
And 0's are printed as 0, not 00, e.g. I got something like 1 0 F2 5 2A 1 0 0 0 43 41 4 96, which is not so good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.