🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

How to enter a C++ floating point constant as a bit pattern.

Started by
4 comments, last by Valakor 3 years, 4 months ago

For various reasons I am using IEEE754 32-floating point numbers such as:

‘the closest value to 2 less than 2’ - represented by the bit pattern 0x3fffffff,

‘the value just below 1/root(2)’ - represented by the bit pattern: 0x3f3504f3

and other constants. Im using C++ in VS2019, and Id like to have the HLSL operator ‘asfloat’ and say something like:

const float belowTwo = asfloat(0x3fffffff);

Of course I could do the horrible:

unsigned int gumf = 0x3fffffff; float belowTwo = *(float *)&gumf;

But I would have to get rid of the constness. And this is just…. nasty….

The only other way I could do in VS2019 is to use the c++17 floating point constant format that was added, and do something like:

const float oneOverRootTwo = 0xb504f3.0p-24; // bit pattern: 0x3f3504f3 = just below 1/root(2)

And write a simple utility to generate the constant code. Which is what I am currently using,

So… is there any way to enter floating point constants as bit patterns directly ? - I understand that it could be argued that the underlying implementation of float is not the language… so they might avoind supporting it, but it just makes things messy when it is needed,,,,

Cheers

Advertisement

I'm not really sure what you're trying to do but I think what you want is called “type punning”. I believe C++ doesn't technically support type punning, however a lot, if not most compilers do support it and Visual Studio seems to. I use this in a number of places and it hasn't failed me so far. The way I typically do this is with a union. I've read that if you use a union the compiler is better able to figure out what you are trying to do, but don't quote me on that.

have you tried an union ? 
union float_uint
{
 float float_value;
 unsigned int uint_value;
};
float_uint test;
test.float_value = 0.5f;
printf("%u %f\n", test.uint_value, test.float_value);  

Great thanks!! - The union idea worked. I added a ctor to the union and then I can define a const…

union float_uint
{ 
   float float_value; 
   unsigned int uint_value;  

   float_uint(unsigned int c): uint_value(c){}; 
};
  
const  float_uint  belowTwo( 0x3fffffff);      //  just below 2

Could you use hex float literals? https://en.cppreference.com/w/cpp/language/floating_literal

Edit: I see you already mentioned these oops - it is certainly less convenient than a simple hex tofloat conversion.​

This topic is closed to new replies.

Advertisement