Reputation: 3
I am working on a project where I read data which is written into memory by a Delphi/Pascal program using memory mapping on a Windows PC. I am now mapping the memory again using pythons mmap and the handle given by the other program and as expected get back a bytestring.
I know that this should represent 13 8-byte floating-point numbers but I do not know how I could correctly convert this bytestring back into those. I also know the aproximate value of the floating-point numbers to check my results.
The code I am using to get the bytestring looks like this:
import mmap
import time
size_map = 13*8
mmf_name = "MMF"
mm = mmap.mmap(-1, size_map, mmf_name, access=mmap.ACCESS_READ)
while True:
mm.seek(0)
mmf = mm.read()
print(mmf)
time.sleep(0.04)
mm.close()
For now I am just running the code again every 40 ms because the data is written every 40 ms into memory.
The output looks something like this:
b'\xcd\xcc\xcc\xe0\xe6v\xb9\xbf\x9a\x99\x99!F\xcd&@\xf5\xa2\xc5,.\xaf\xbd\xbf\x95\xb0\xea\xb5\xae\n\xd9?333/\x9b\x165@\x00\x00\x00h\x89D1\xc08\xd1\xc3\xc3\x92\x82\xf7?tA\x8fB\xd6G\x04@]\xc1\xed\x98rA\x07@\x9a\x99\x99\x99\x99\x191@\x00\x00\x00\xc0\xcc\xcc=@\x00\x00\x00\xc0\x1eE7@\x00\x00\x00\x00\xb8\x1e\x1a@'
I tried struct.unpack()
, .decode()
and float.fromhex()
to somehow get back the right value but it didn't work. For example the first 8 bytes should roughly represent a value between -0.071 and -0.090.
The problem seems to be very basic but I still wasn't able to figure it out by now. I would be very grateful for any suggestions how to deal with this and get the right floating-point values from a bytestring. If I am missing any needed Information I am of course willing do give that too.
Thank you!
Upvotes: 0
Views: 265
Reputation: 644
Try using numpy
s frompuffer
function. You will get an array you can than read:
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html
import numpy as np
buffer = b'\xcd\xcc\xcc\xe0\xe6v\xb9\xbf\x9a\x99\x99!F\xcd&@\xf5\xa2\xc5,.\xaf\xbd\xbf\x95\xb0\xea\xb5\xae\n\xd9?333/\x9b\x165@\x00\x00\x00h\x89D1\xc08\xd1\xc3\xc3\x92\x82\xf7?tA\x8fB\xd6G\x04@]\xc1\xed\x98rA\x07@\x9a\x99\x99\x99\x99\x191@\x00\x00\x00\xc0\xcc\xcc=@\x00\x00\x00\xc0\x1eE7@\x00\x00\x00\x00\xb8\x1e\x1a@'
nparray = np.frombuffer(buffer, dtype=np.float64)
nparray
array([ -0.09947055, 11.40092568, -0.11595429, 0.39127701, 21.08830543, -17.26772165, 1.46937825, 2.53507664, 2.90695686, 17.1 , 29.79999924, 23.27000046, 6.52999878])
nparray[0]
-0.09947055
Upvotes: 1