psihodelia psihodelia - 10 months ago 123
Python Question

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

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

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

  2. How to write array of integers L
    into a binary file using write()?

Answer Source

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":
with open("data", "wb") as f:
# Read from file again
b = array.array("h")
with open("data", "rb") as f:
    b.fromfile(f, 10)
if sys.byteorder == "little":