how to convert from network to host byte order

Peter Otten __peter__ at web.de
Thu Mar 5 07:48:19 EST 2009


Evan wrote:

> Hello ~
> 
> I'm new with python,  what my problem is, I have a binary file, I want
> to read first 2 bytes and convert it to host byte order, then write it
> to another file.
> 
> I try to use 'socket' and 'struct', but somehow i can not get it
> working fine:
> 
> for example, totally I'm not sure if my steps is correct or not:
> ++++++++++++++++++++++++++++++++++++++++++++++++
>>>> import socket
>>>> f=open('a.bin','rb')
>>>> f.read(2)
> '\x04\x00'
> 
>>>> f.seek(0)
>>>> st=f.read(2)
>>>> e=open('test.bin','w+b')
>>>> e.write(socket.ntohs(struct.unpack('H',st[: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
> +++++++++++++++++++++++++++++++++++++++++++++++++
> 
> It failed due to the parameter is 'int', not 'str' in write function.
> but how can i do that?
> 
> Thanks,
> Evan

I think for just 2 bytes I'd do it manually:

a = open(...).read(2)
if sys.byteorder == "little":
    a = a[::-1]
open(...).write(a)

For larger chunks of data I'd use a byte array and the byteswap() method,
see

http://docs.python.org/library/array.html

Peter



More information about the Python-list mailing list