how to convert from network to host byte order

Mark Tolonen metolone+gmane at gmail.com
Thu Mar 5 10:55:53 EST 2009


"Evan" <xdicry at gmail.com> wrote in message 
news:79582a34-5d0b-49b2-8c1e-4139324ff523 at b38g2000prf.googlegroups.com...
> 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.


There is a piece of information missing here.  What is the byte order of the 
original binary 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'


This is either a little-endian 4, or a big-endian 1024 (0x400).


>>>> 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?

socket.ntohs returns an integer.  write takes a string.  ntohs assumes the 
original value was big-endian (network) order.

If the original binary file is little-endian, this works:

import struct
f=open('a.bin','rb')
data = struct.unpack('<H',f.read(2))[0]
f.close()
e=open('test.bin','wb')
e.write(struct.pack('H',data)) # default is host-order, could be big or 
little.
e.close()

If the original binary file is big-endian, change the 3rd line:

data = struct.unpack('>H',f.read(2))[0]

-Mark






More information about the Python-list mailing list