I’m looking to for a reasonably efficient way of determining if a floating point value (double) can be exactly represented by an integer data type (long, 64 bit).
My initial thought was to check the exponent to see if it was 0 (or more precisely 127). But that won’t work because 2.0 would be e=1 m=1…
So basically, I am stuck. I have a feeling that I can do this with bit masks, but I’m just not getting my head around how to do that at this point.
So how can I check to see if a double is exactly representable as a long?
Thanks
Here’s one method that could work in most cases. I’m not sure if/how it will break if you give it
NaN,INF, very large (overflow) numbers…(Though I think they will all return false – not exactly representable.)
You could:
Something like this:
floor()andceil()are also fair game (though they may fail if the value overflows an integer):And here’s a messy bit-mask solution:
This uses union type-punning and assumes IEEE double-precision. Union type-punning is only valid in C99 TR2 and later.