How to write an array containing both positive and negative integers into the binary file. Each integers must be written in two bytes. And how to read that binary file by converting the bytes back into the integers.
example: arr=[-32767,-32789,-1200,0,6789,34589] ->input array each value must be converted into two bytes and are written into the binary file "binaryfile.bin"
now the requirement is to read entire file ( "binaryfile.bin") and convert those bytes into values and print it as an array outputarray=[-32767,-32789,-1200,0,6789,34589]
CodePudding user response:
Numpy can help you with that:
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tobytes.html
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html
See the following example:
import numpy as np
arr = np.array([-32767,-32789,-1200,0,6789,34589], dtype=np.int16)
arr_bytes = arr.tobytes()
with open("binaryfile.bin", mode="wb") as file:
file.write(arr_bytes)
with open("binaryfile.bin", mode="rb") as file:
my_bytes = file.read()
np.frombuffer(my_bytes, dtype=np.int16)
Note that the number 34589
is larger than 2^15 and therefore cannot be stored as signed integer of two bytes it will be converted to -30947
(integer overflow). You could store a second array indicating which number is a signed or an unsigned integer, but this could become more complicated than jsut storing integer 32.
Note: As a small warning when sharing binary files with other people, please also be sure that you agree on the byte order, see https://en.wikipedia.org/wiki/Endianness
CodePudding user response:
import numpy as np
base_array=[]
for i in range(-32768,32767 1):
base_array.append(i)
**#INPUT FILE CREATION**
arr = np.array(base_array, dtype=np.int16)
arr_bytes = arr.tobytes()
with open("binaryfile.bin", mode="wb") as file:
file.write(arr_bytes)
# To read the file
with open("binaryfile.bin", mode="rb") as file:
my_bytes = file.read()
#bytes are converted into int16 type and are stored in outputarray
outputarray=[]
outputarray=np.frombuffer(my_bytes, dtype=np.int16)
print(outputarray) `