convert binary string to numpy array

后端 未结 1 1047
余生分开走
余生分开走 2020-12-02 23:04

Assume I have the string:

my_data = \'\\x00\\x00\\x80?\\x00\\x00\\x00@\\x00\\x00@@\\x00\\x00\\x80@\'

Where I got it is irrelevant, but for

相关标签:
1条回答
  • 2020-12-02 23:52
    >>> np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4') # or dtype=np.dtype('<f4'), or np.float32 on a little-endian system (which most computers are these days)
    array([ 1.,  2.,  3.,  4.], dtype=float32)
    

    Or, if you want big-endian:

    >>> np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4') # or dtype=np.dtype('>f4'), or np.float32  on a big-endian system
    array([  4.60060299e-41,   8.96831017e-44,   2.30485571e-41,
             4.60074312e-41], dtype=float32)
    

    The b isn't necessary prior to Python 3, of course.

    In fact, if you actually are using a binary file to load the data from, you could even skip the using-a-string step and load the data directly from the file with numpy.fromfile().

    Also, dtype reference, just in case: http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

    0 讨论(0)
提交回复
热议问题