Fredrik Lundh fredrik at
Wed Aug 20 19:55:26 CEST 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:
>    # 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",
    length = result[0]

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

see the struct documentation for more options.

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

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

    width, height = struct.unpack("!ii",


More information about the Python-list mailing list