简体   繁体   中英

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]);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM