pythonmatlabtypestype-conversionsingle-precision

What is the equivalent of Matlab/Octave single type cast function in Python


I have received the data from a socket. In Matlab, this data is converted into single precision by the following function

data_cal_rx = typecast(data_tcp2, "single");

Now I would like to have the same function in Python. Searching from google and Stack overflow, I saw that the single precision in Python is numpy.float32. So I replace by the following function:

import numpy as np
data_cal_rx = np.float32(data_tcp2)

data_tcp2 in Matlab is an array interger numbers with: class: uint8 dimension: 1x70848

however, when I received data_tcp2 by socket in Python, it is displayed as:

... \x00\x00C\x00 QE\x00 \x04E\x00 'E\x00BE\x00D\x00\x00LE\x00\x00\x10*E\x00`\x00@D\x00\x10+\x00\x00C\x000I\x00\x00A\x00\x16\x00\x13\x00 ...

And I got this error from the terminal in python:

ValueError: could not convert string to float:

It could be a problem with socket in python? Any help or idea would be greatly appreciated.

Thank you very much


Solution

  • As an example, let's start with 32-bit float array:

    orig = np.arange(5, dtype=np.float32)
    

    We'll convert this to a buffer of bytes:

    data = orig.tobytes()
    

    This is shown as:

    b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
    

    Note the initial "b", which indicates this is a bytes object, not a string. If your data is actually a string, see at the bottom of this answer.

    Now that we've got our buffer of bytes containing the data in the array, we can convert this back to an array of 32-bit floating-point values with:

    out = np.frombuffer(data, dtype=np.float32)
    

    (out is now identical to orig).


    If data is a string, you need to first cast it to a bytes buffer, which you can do with

    data = bytes(data, 'latin1')
    

    The "latin1" part is the encoding. This encoding seems to not change any data when converting from string to bytes.