Question

How to extract data which is in float32 format (in the interval [-1, +1]) to an int32 which is in [-2^31, 2^31-1] ?

Here is what I want to do (but more efficiently, i.e. without multiplications / conversions if possible) :

f = struct.unpack('f', data)   # data is in IEEE float32 format
f *= 2**31
out = int(myfloat)

Example :

This is the float 0.000000000 : 00 00 00 00

This is the float 1.000000000 : 00 00 80 3F

This is the float -0.000000000 : 00 00 00 80

This is the float -1.000000000 : 00 00 80 BF

Why these numbers for coding 1.000000 ?


Note : This can be useful for audio application, where .wav 32 bits IEEE float have to live togethter with regular 32 bits integer .wav files.

PS : I recently asked a question about float numpy array -> int numpy array conversion here : From IEEE32 float to 32bit integer numpy array (example : audio .wav files), but now I realize that this problem is not numpy-specific, hence this more general question here.

Was it helpful?

Solution

You can add your list with floats into an array and then define dtype, in this case 'int32'. Also note that in Numpy the dtype for float is 'float64'.

from numpy  import *


float_data_list = [1.2, 3.5, 5.1]



matrice = array(float_data_list, dtype ='int32' ) # define dtype
print matrice

output: [1 3 5]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top