Discussion:
Convert floating point number to an int and then back again.
(too old to reply)
Nic
2010-09-30 15:59:01 UTC
Permalink
Hello,
I'm wandering how to store a floating point number (float) in an int
and then convert it back to the origional floating point number again.
From what I understand, if I cast to int (int i = (int)floatnumber)
this will round the number down to the nearest whole number which is
not want I'm looking for. Can this be done?
Thanks in advance
Nic
Chris Shearer Cooper
2010-09-30 16:44:48 UTC
Permalink
Post by Nic
Hello,
I'm wandering how to store a floating point number (float) in an int
and then convert it back to the origional floating point number again.
From what I understand, if I cast to int (int i = (int)floatnumber)
this will round the number down to the nearest whole number which is
not want I'm looking for. Can this be done?
Thanks in advance
Nic
So ... if you start with a floating point number like 3.524, and you
jam that into an int, you will pretty much end up with either 3 or 4.
If you want to store 3.524 intact, an int can't do that.

Now you can get clever and think of ways to store an approximation of
your original floating point number that fits within 32 bits (the size
of an integer). For example, if your floating point number is a
dollar figure like $3.53, just store floating * 100 in your int, and
then you can take int / 100.0 to get back something darn close to your
original floating point number.

Chris
David Lowndes
2010-09-30 16:49:03 UTC
Permalink
Post by Nic
I'm wandering how to store a floating point number (float) in an int
and then convert it back to the origional floating point number again.
A single precision 32-bit float value can be stored in the same space
as a 32-bit integer.

Why are you trying to do something so odd?

Dave
Ulrich Eckhardt
2010-10-01 07:00:21 UTC
Permalink
Post by Nic
I'm wandering how to store a floating point number (float) in an int
and then convert it back to the origional floating point number again.
It could be that a float requires more bits than an int provides, making
this impossible.
Post by Nic
From what I understand, if I cast to int (int i = (int)floatnumber)
this will round the number down to the nearest whole number which is
not want I'm looking for.
Any experimentation will show you the truth of that. ;)


Anyhow,

typedef ... uint_float_t; // some integer of same size as the float
float const f = 3.141f;
uint_float_t const i = reinterpret_cast<uint_float_t const&>(f);
float const f2 = reinterpret_cast<float const&>(i);

This should do the job.

However, I don't think it's a good idea to do so for various reasons of
portability. If you explained your goals you would get better suggestions
how to achieve them.

Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite

Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
Loading...