Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print binary file as bytes?

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.)

like image 602
h__ Avatar asked Apr 12 '13 06:04

h__


1 Answers

>>> 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'
like image 114
NPE Avatar answered Oct 17 '22 15:10

NPE