how to convert from network to host byte order

Philipp Hagemeister phihag at phihag.de
Thu Mar 5 14:50:19 CET 2009


-----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" in
http://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-----



More information about the Python-list mailing list