Big-endian binary data to/from Python ints?

Matt Nordhoff mnordhoff at mattnordhoff.com
Wed Dec 26 18:38:53 EST 2007


William McBrine wrote:
> Here are a couple of functions that I feel stupid for having written. 
> They work, and they're pretty straightforward; it's just that I feel like 
> I must be missing an easier way to do this...
> 
> def net_to_int(numstring):
>     """Convert a big-endian binary number, in the form of a string of
>     arbitrary length, to a native int.
>     """
>     num = 0
>     for i in numstring:
>         num *= 256
>         num += ord(i)
>     return num
> 
> def int_to_net(num):
>     """Convert a native int to a four-byte big-endian number, in the form
>     of a string.
>     """
>     numstring = ''
>     for i in xrange(4):
>         numstring = chr(num % 256) + numstring
>         num /= 256
>     return numstring
> 
> The situation: I'm getting a four-byte packet from a socket that consists 
> of a big-endian 32-bit integer. (It specifies the length of the data that 
> follows.) I have to send the same thing in reply. send() and recv() work 
> with strings... I'm familiar with ntohl() and htonl(), but those expect/ 
> return integers.

The struct module should do it, but do you prefer your code or format
strings? :-P

<http://docs.python.org/lib/module-struct.html>
-- 



More information about the Python-list mailing list