[PYTHON/BINARY FILE]: Sorting the bits read

Question:

The file ‘binary_file.bin’ contains the following binary data (hexadecimal base used for simplicity):

A43CB90F

Each 2 bytes correspond to an unsigned integer of 16 bits: first number is A43C and second number is B90F, which in decimal base correspond respectively to 42044 and to 47375. I’m trying to read the binary input stream in Python using the method fromfile() from the numpy library as follows:

import numpy as np
binary_stream = open('binary_file.bin', 'rb')
numbers_to_read=2
numbers = np.fromfile(binary_stream,dtype=np.uint16,count=numbers_to_read,sep="") 
print(numbers[0]) # Result -----> DECIMAL: 15524 / HEXADECIMAL: 3CA4
print(numbers[1]) # Result -----> DECIMAL: 4025 / HEXADECIMAL:  0FB9

The first number read corresponds to 3CA4 instead of A43C, and the second number read corresponds to 0FB9 instead of B90F. So, it looks like the bytes are flipped when reading them with fromfile(). Is there any alternative to make sure that the bytes come in the same order as in the binary file? First number should be A43C (42044) and the second number should be B90F and the bytes shouldn’t get flipped.

Asked By: jaj_develop

||

Answers:

You need to specify the byteorder of the data type.

For example:

import numpy as np
binary_stream = open('/tmp/binary_file.bin', 'rb')
numbers_to_read=2
numbers = np.fromfile(binary_stream,
                      dtype=np.dtype('>H'),
                      count=numbers_to_read,
                      sep="") 
for num in numbers:
    print(f"Decimal = {num} | Hex = {num:04X}")

Which gives the following output:

Decimal = 42044 | Hex = A43C
Decimal = 47375 | Hex = B90F
Answered By: ukBaz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.