Converting float to 32bit signed Integer value? (newbie)

Paul Rubin http
Sat Oct 11 13:34:19 EDT 2003


"MangoMan" <mangoman at kitsuneaye.co.uk> writes:
> value = float(self.buffer32.pop(0))
> 
> e.g instead of getting a value like 2.456 i get 2

Well yes, 2.456 isn't an integer, so you can't have read it in as an
integer.  If you read in 2 as an integer and convert it to float, you
get 2.0.

> How could i properly extract floats from this buffer in phython?
> Additionally, how could i store floats into this buffer? 
> e.g(which doesn't work) :
> 
> value = 2.234
> self.buffer32.append(int(value))

You need to use array('f') and not array('i') if you want an array of
floats.

> (In the C code, the float is written to the buffer using a typecast,
> e.g buff[pos] = (int)value)

If buff is an array of ints and value is a (float)2.3456, that
conversion will throw away the fractional part and set buff[pos] to 2.
If you're really trying to jam a floating point bit pattern into an
int buffer, you have to explicitly bypass the conversion, e.g.:

    buff[pos] = *((int *) &value)




More information about the Python-list mailing list