ascii2dec

U

Uwe Mayer

Hi,

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
Uwe
--
 
U

Uwe Mayer

Uwe said:
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

Sorry, socket.htonl(...) already expects a number, so its:
#convert 4 bytes to integer
length=socket.htonl(length) # swap bytes

i.e.
How to convert:

length = '\x01\x00\x00\x00'

to an integer

Uwe
--
 
F

Fredrik Lundh

Uwe said:
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>
 
P

Peter Hansen

Uwe said:
Sorry, socket.htonl(...) already expects a number, so its:


i.e.
How to convert:

length = '\x01\x00\x00\x00'

to an integer

Use the struct module, with appropriate "endianism".

-Peter
 
S

Sean Ross

Uwe Mayer said:
Uwe Mayer wrote:
How to convert:

length = '\x01\x00\x00\x00'

to an integer


As Peter suggested, use struct.unpack with the appropriate endianness, e.g.
import struct
length = '\x01\x00\x00\x00'
# convert 'length' to signed integer (big-endian)
unpacked = struct.unpack('>i', length)[0] # unpack returns a tuple
unpacked 16777216
# convert 'length' to signed integer (little-endian)
unpacked = struct.unpack('i', length)[0] # or, fmt = '<i'
unpacked
1

HTH
Sean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top