How to convert binary file data?

Darrell news at dorb.com
Tue May 8 21:51:52 EDT 2001


Try this.

buf=open(fn,'rb').read()

for x in range(20):
    if x % 5 == 0:
        print
    print "(%s, 0x%x),"%(buf[x], ord(buf[x])),


"DOC"  wrote
>
> >>># read in 1 byte:
> ...buf=x.read (1)
>
> >>># this is what's in buf
> ... buf
> '\xe0'
>
This is the byte 0xe0

> >>># try the eval
> ...eval (buf)
> Traceback...
> ...
> SyntaxError: unexpected EOF while parsing
>
The byte 0xe0 isn't valid Python, so eval won't work.

> >>># OK try string.atoi!
> ...string.atoi (buf)
> Traceback...
> ...
> ValueError: invalid literal for int():
>
The byte 0xe0 isn't an ASCII representation of a number.


--Darrell






More information about the Python-list mailing list