RE: [GD-General] The joy of type aliasing and C
Brought to you by:
vexxed72
|
From: Brian H. <ho...@py...> - 2003-12-30 17:54:00
|
> 2) What is the most portable way (that avoids risk of alias
> optimisation) of getting a float into binary representation, in
> native form and/or a particular standard form (IEEE, etc.)?
float f =3D 1.0f;
const unsigned char *c =3D ( const unsigned char * ) &f;
int i;
for ( i =3D 0; i < sizeof( f ); i++ )
{
store_some_byte( c[ i ] );
}
That is 100% legal, as long as it stays in char form. That is how
you're expected to transmit it over, say, a network connection if
necessary, assuming the machine on the other side understands the same
floating point format.
Floating point in the C standard is borderline disastrous.
Factoid #1: signed integer representation is not specified in the
standard, so you could conceivably run on a system with, say,
ones-complement arithmetic.
Factoid #2: C99 introduced support for IEEE-754 floating point
operations and formats officially, but it's an optional extension that
can be examined by checking __STDC_IEC_559__
Factoid #3: There's a standard #pragma to tell the compiler not to
dork with the floating point control and status words while you do
stuff that relies on that state remaining constant.
Brian
|