"Stein Gulbrandsen" <stein@homewrote in message
news:45******@news.broadpark.no...
: What is the best way to get to the integer representation of a float?
:
: I would like to do
: int& toIntByCast (float& a) {return *reinterpret_cast<int*(&a);}
: but is this legal?
Formally, behavior will be undefined.
: Is this safer?
: int toIntByUnion (const float& a) {
: union {float f; int i;} u = {a};
: return u.i;
: }
This would probably even be less portable.
: Or are there better ways?
The first option displayed above is used often, and will
"work" as you expect on most platforms. The union trick
is just more complicated and not better in any way.
Formally, the correct way to access the representation
of an object (here a float) is to access it as an array
of 'unsigned char':
unsigned char* p = (unsigned char*)aFloat;
for( int i = 0 ; i<sizeof(aFloat) ; ++i )
... read p[i];
hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com