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

M

MangoMan

Hi there,

Currently i am reading an array of signed int's from a file :

fs = open("somefile", "rb")
self.buffer32 = array('i')
self.buffer32.fromfile(fs)
# ...
fs.close()

However, i need to read a float from this array, but of course, the
following code does not work :

value = float(self.buffer32.pop(0))

e.g instead of getting a value like 2.456 i get 2

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))

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

Thanks for any help,
-MangoMan
 
P

Paul Rubin

MangoMan said:
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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top