ascii2dec

Fredrik Lundh fredrik at pythonware.com
Wed Aug 20 13:55:26 EDT 2003


Uwe Mayer wrote:

> this must sound stupid to you, but I'm ages out of Python and I just can't
> find a function to convert 4 bytes of binary data to an integer value:
>
> length=f.read(4)    # get length in binary
> length=socket.htonl(length)    # swap bytes
>
> #convert 4 bytes to integer
>
> f.close()
>
> Thanks for any help

    import struct
    result = struct.unpack("!i", f.read(4))
    length = result[0]

where "!" means network byte order, and "i" means 32-bit integer.

see the struct documentation for more options.

if the f.read fails to read 4 bytes, this operation raises a struct.error
exception

note that unpack returns a tuple; you may prefer to unpack a bunch
of fields in one step:

    width, height = struct.unpack("!ii", f.read(8))

</F>








More information about the Python-list mailing list