Search code examples
c++floating-pointfloating-accuracyieee-754notation

define double constant as hexadecimal?


I would like to have the closest number below 1.0 as a floating point. By reading wikipedia's article on IEEE-754 I have managed to find out that the binary representation for 1.0 is 3FF0000000000000, so the closest double value is actually 0x3FEFFFFFFFFFFFFF.

The only way I know of to initialize a double with this binary data is this:

double a;
*((unsigned*)(&a) + 1) = 0x3FEFFFFF;
*((unsigned*)(&a) + 0) = 0xFFFFFFFF;

Which is rather cumbersome to use.

Is there any better way to define this double number, if possible as a constant?


Solution

  • Hexadecimal float and double literals do exist. The syntax is 0x1.(mantissa)p(exponent in decimal) In your case the syntax would be

    double x = 0x1.fffffffffffffp-1