Changing endian format

A

Amit Gaur

Hi newbie to python here,
I have a binary file and i need to change the endian format..little to big as well as vice versa..could anyone help me out.
thanks
 
D

David M. Wilson

Amit Gaur said:
Hi newbie to python here,
I have a binary file and i need to change the endian format..little to big as well as vice versa..could anyone help me out.

If you use the struct module to read the file, this appears to be
handled for you.

http://python.org/doc/current/lib/module-struct.html


Example (pack the value 1234 into an unsigned long in little endian,
then big endian format):

py> import struct
py> struct.pack('<L', 1234)
'\xd2\x04\x00\x00'
py> struct.pack('>L', 1234)
'\x00\x00\x04\xd2'


See also 'struct.unpack', 'socket.htons', and 'socket.htonl'.
 
M

Miki Tebeka

Hell Amit,
I have a binary file and i need to change the endian format..little to big as
well as vice versa..could anyone help me out.
Warning: Not tested!

#!/usr/bin/env python
from sys import argv
from array import array

a = array("H", open(argv[1], "rb").read())
a.byteswap()
open(argv[2], "wb").write(a.tostring())

HTH.
Miki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top