Nicolas Heimann
Nicolas Heimann

Reputation: 2581

Convert numpy unit8 raw array directly to float32

In my situation I get a numpy.ndarray as unit8 of size 4 * n which represents raw binary data of float32 entities. So 4 items together represent one float32. To get float32 numbers I currently convert uint8 raw data to a binary string and than read from this string the float32 values.

np.fromstring(raw_unit8_data.tostring(), dtype='<f4')

Is there a possibility to do this conversion directly without converting the uint8 data to a string first?

Upvotes: 5

Views: 8694

Answers (1)

Alex Riley
Alex Riley

Reputation: 176938

You could use view to have NumPy reinterpret the raw data as the appropriate data type. For example:

>>> raw_unit8_data = np.array([32, 14, 135, 241], dtype='uint8')
>>> raw_unit8_data.view('<f4')
array([ -1.33752168e+30], dtype=float32)

This has the advantage of not using any temporary arrays or buffers (we're just changing how the memory is read) and gives the same values as your current method:

>>> np.fromstring(raw_unit8_data.tostring(), dtype='<f4')
array([ -1.33752168e+30], dtype=float32)

Upvotes: 6

Related Questions