Ramana Reddy
Ramana Reddy

Reputation: 399

How to print hex dump from a buffer in python?

I have a python snippet like this:

siz=len(ret)
for i in range(0,siz-1):
       print "%s " % ret[i],

When I use %s it works fine and prints some alien characters on the console!!

But how do I print hex dump of it.

I tried:

print "%02x " % ret[i],

print "%02x " % hex(ret[i]),

print format(ret[i],'02x'),

print format(hex(ret[i],'02x'),

print "%02x " % hex(int(ret[i])),

All these things resulted in errors.

A similar question is asked here but those answers didn't help me.

How do I do this similar to c style printf("%02x ",ret[i]);

Upvotes: 1

Views: 2426

Answers (1)

agold
agold

Reputation: 6276

I think you are looking for the character code which you can obtain with ord, then you can apply your method to print the character code hexadecimal:

ret="#~½|"
for c in ret:
   print "%s  -  %02x" % (c,ord(c))

Which gives as output:

#  -  23
~  -  7e
�  -  c2
�  -  bd
|  -  7c
4  -  34

Upvotes: 2

Related Questions