float bits and strict aliasing

后端 未结 4 1771
抹茶落季
抹茶落季 2020-12-01 09:29

I am trying to extract the bits from a float without invoking undefined behavior. Here is my first attempt:

unsigned foo(float x)
{
    unsigned* u = (unsign         


        
4条回答
  •  天命终不由人
    2020-12-01 09:57

    About the only way to truly avoid any issues is to memcpy.

    unsigned int FloatToInt( float f )
    {
       static_assert( sizeof( float ) == sizeof( unsigned int ), "Sizes must match" );
       unsigned int ret;
       memcpy( &ret, &f, sizeof( float ) );
       return ret;
    }
    

    Because you are memcpying a fixed amount the compiler will optimise it out.

    That said the union method is VERY widely supported.

提交回复
热议问题