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

I need to read and write binary data, where each data item is:

  • size = 2 bytes (16 bits)
  • coding = signed 2 add-ons
  • endiannes = large or small (should be optional)

Is this possible without using an external module? If yes,

  • How to read such data from a binary file using read () into an array of L of integers?
  • How to write an array of integers L to a binary using write ()?
+5
source share
5 answers

, array. , array.byteswap() , sys.byteorder . :

# 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()
+10
from array import array
# Edit:
from sys import byteorder as system_endian # thanks, Sven!
# Sigh...
from os import stat

def read_file(filename, endian):
    count = stat(filename).st_size / 2
    with file(filename, 'rb') as f:
        result = array('h')
        result.fromfile(f, count)
        if endian != system_endian: result.byteswap()
        return result
+2

struct.unpack(byteorder + str(len(rawbytes) // 2) + "h", rawbytes)

byteorder - '<' '>' , . . , , array, , array byteswap.

+1

/ numpy:

import numpy as np

sys.argv[1] = endian # Pass endian as an argument to the program
if endian == 'big':
    precTypecode = '>'
elif endian == 'little':
    precTypecode = '<'

# Below: 'i' is for signed integer and '2' is for size of bytes. 
# Alternatively you can make this an if else statement to choose precision
precTypecode += 'i2'

im = np.fromfile(inputFilename, dtype = precTypecode) # im is now a numpy array
# Perform any operations you desire on 'im', for example switching byteorder
im.byteswap(True)
# Then write to binary file (note: there are some limitations, so refer doc)
im.tofile(outputFilename)

, .

0

, - :

with open("path/file.bin", "rb") as file:
    byte_content = file.read()
    list_16bits = [byte_content[i + 1] << 8 | byte_content[i] for i in range(0, len(byte_content), 2)]

. , , 2 . , i+1 i

0
source

All Articles