Search code examples
pythonpython-3.xsocketsudp

Converting Bytes to float format


I have the following data from a datagram message received by UDP socket:

b'/13/raw\x00,ffffffffffffff\x00=\xca\x00\x00=[\x00\x00\xbf\x82H\x00B\x14\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00B;\x81\n\xbf\xbat4C-\xfd\xb0B\x87\xac\xd9\x00\x00\x00\x00E\xcd\xc0\x00I\xcc\xc1\xe0'

This is my code:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((IP, p))
print("Listening for UDP packets on {0}:{1} ...".format(IP, p))
while 1:
    rawdata, _ = sock.recvfrom(1024)
    print(rawdata)

How can I convert rawdata to floats?

This is the data type that I am expecting: enter image description here

Both are different samples!

Thank you


Solution

  • each float is 4 bytes of data (typically... not always... again you need to consult the docs for whatever p[ayload you need)

    but assuming that /13/raw is easy enough for you and the rest is what you need to decode

    if we assume that \x00 is some sort of delimiter we are left with the bytestring as follows

    msgBytes = b',ffffffffffffff\x00=\xca\x00\x00=[\x00\x00\xbf\x82H\x00B\x14\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00B;\x81\n\xbf\xbat4C-\xfd\xb0B\x87\xac\xd9\x00\x00\x00\x00E\xcd\xc0\x00I\xcc\xc1\xe0'
    

    we can see there are 72 characters which means 18 floats (18*4 === 72)

    however your expected output only seems to have 14 floats so that means 16 bytes are some sort of metadata (maybe a checksum, or some payload information (how many floats to expect))

    we can just struct unpack it as floats now ... but i dont get your "expected value" so some of those may be doubles or something other than 4 byte floats

    floats = struct.unpack('18f',msgBytes)

    now you have a list of 18 floats ... but again not matching your expected output, it may be related to endianness or some other method that you need to do additional processing on (eg maybe it should be ints and they become floats by dividing by 100 or something?)

    [edit] investigating further I suspect ffffffffff\x00 is some sort of header or metadata so if we start with

    myBytes = b'=\xca\x00\x00=[\x00\x00\xbf\x82H\x00B\x14\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00B;\x81\n\xbf\xbat4C-\xfd\xb0B\x87\xac\xd9\x00\x00\x00\x00E\xcd\xc0\x00I\xcc\xc1\xe0'
    

    and unpack it with struct.unpack('14f',myBytes) we get 14 floats as expected ... some are zero like in your example ... but the rest dont match

    (7.254942539348875e-41, 3.273012823123475e-41, 6.659058584274783e-39, 1.1762210642058864e-38, 0.0, 0.0, 0.0, 1.244453845292514e-32, 2.2792208653754642e-07, -1.84210369180704e-09, -6070301691478016.0, 0.0, 1.7706052095336117e-38, -1.1171693447134314e+20)
    

    so I think we still dont have enough info to actually answer this question, need to know more about the datasource and other stuff