Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read/write binary 16-bit data in Python 2.x?

Tags:

python

binary

I have to read and write binary data, where each element of data:

  • size = 2 bytes (16 bit)
  • encoding = signed 2's complement
  • endiannes = big or little (must be selectable)

Is it possible without using any external module? If yes,

  1. How to read such data from a binary file using read() into an array L of integers?
  2. How to write array of integers L into a binary file using write()?
like image 669
psihodelia Avatar asked Feb 17 '11 15:02

psihodelia


People also ask

How do I read or write binary data in Python?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing.

How do you read and write binary data?

Initialize the variables with data. If file open successfully, write the binary data using write method. Close the file for writing. Open the binary file to read.

What is binary format in Python?

"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default.


1 Answers

I think you are best off using the array module. It stores data in system byte order by default, but you can use array.byteswap() to convert between byte orders, and you can use sys.byteorder to query the system byte order. Example:

# Create an array of 16-bit signed integers
a = array.array("h", range(10))
# Write to file in big endian order
if sys.byteorder == "little":
    a.byteswap()
with open("data", "wb") as f:
    a.tofile(f)
# Read from file again
b = array.array("h")
with open("data", "rb") as f:
    b.fromfile(f, 10)
if sys.byteorder == "little":
    b.byteswap()
like image 149
Sven Marnach Avatar answered Sep 18 '22 15:09

Sven Marnach