2009/5/27 Michael Meissner <meissner@xxxxxxxxxxxxxxxxxx>: > On Tue, May 26, 2009 at 09:42:40PM -0700, me22 wrote: >> >> In my experience compilers are often even smart enough to have this >> avoid the memory roundtrip, and it's undeniably legal: >> >> int ftoi(float x) { >> int i; >> memcpy(&i, &x, 4); >> return i; >> } > > Well from a pedantic point of view, it is only legal if sizeof (i) == sizeof > (x) == 4, but you presumably already know that. > Agreed; I assumed we were operating under the ever-popular "there's nothing but windows and linux on x86 or x64" delusion. Of course, the union and other tricks are also architecture-dependant. If I really wanted to do it properly, I'd use something like this: template <typename F> typename boost::uint_t<sizeof(F)*CHAR_BIT>::least bitcast_to_integral(F f) { typename boost::uint_t<sizeof(F)*CHAR_BIT>::least i = 0; void *p = &i; #ifdef BOOST_BIG_ENDIAN p = (char*)p + (sizeof(i)-sizeof(f)); #endif std::memcpy(&i, &f, sizeof(F)); return i; } But really, anything hacking around in float bit patterns is unlikely to be portable enough to warrant such treatment.