ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Hex dumper
Submitter: Sébastien Keim (other recipes)
Last Updated: 2002/08/05
Version no: 1.0
Category: Text

 

5 stars 5 vote(s)


Description:

Hexadecimal display of a byte stream

Source: Text Source

FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])

def dump(src, length=8):
    N=0; result=''
    while src:
       s,src = src[:length],src[length:]
       hexa = ' '.join(["%02X"%ord(x) for x in s])
       s = s.translate(FILTER)
       result += "%04X   %-*s   %s\n" % (N, length*3, hexa, s)
       N+=length
    return result

s=("This 10 line function is just a sample of pyhton power "
   "for string manipulations.\n"
   "The code is \x07even\x08 quite readable!")

print dump(s)

Discussion:

This function produce a classic 3 columns hex dump of a string.
* The first column print the offset in hexadecimal.
* The second colmun print the hexadecimal byte values.
* The third column print ASCII values or a dot for non printable characters.



Add comment

Number of comments: 1

Small Improvements, Raymond Hettinger, 2005/09/24

def dump2(src, length=8):
    result=[]
    for i in xrange(0, len(src), length):
       s = src[i:i+length]
       hexa = ' '.join(["%02X"%ord(x) for x in s])
       printable = s.translate(FILTER)
       result.append("%04X   %-*s   %s\n" % (i, length*3, hexa, printable))
    return ''.join(result)

Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Treat the Win32 Registry ...

5. a friendly mkdir()

6. Wrapping template engine ...

7. Assignment in expression

8. Changing return value ...

9. Implementation of sets ...

10. bag collection class




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.