how to convert from network to host byte order

Evan xdicry at gmail.com
Thu Mar 5 09:09:47 EST 2009


On Mar 5, 9:50 pm, Philipp Hagemeister <phi... at phihag.de> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA512
>
> Evan wrote:
> >>> inp='\x04\x00'
> >>> out = socket.ntohs(struct.unpack('H',inp[:2])[0]))
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> > TypeError: argument 1 must be string or read-only buffer, not int
>
> Your approach is nearly right. First of all, you have to tell
> struct.unpack it should unpack from network order ("!"):
>
> >>> struct.unpack('!H', inp)[0]
>
> 1024
>
> Then you want to repack it in host byte order. Use "=" for that.
>
> >>> out = struct.pack('=H', struct.unpack('!H', inp)[0])
> >>> out
>
> '\x00\x04'
>
> For more information, look for "Size and alignment" inhttp://docs.python.org/library/struct.html.
>
> Regards,
>
> Philipp Hagemeister
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.9 (GNU/Linux)
>
> iEYEAREKAAYFAkmv2JkACgkQ9eq1gvr7CFymKACghFXMZb9D6pkWZQdapvwTsKJ5
> b0UAn0Uvbcguv/rdxjFKXhMQz22+Notn
> =ZiKx
> -----END PGP SIGNATURE-----

That's good, thanks Philipp



More information about the Python-list mailing list