views:

305

answers:

2

Does anyone have handy the snippets of code to convert an IEEE 754 double to the immediately inferior (resp. superior) float, without changing or assuming anything about the FPU's current rounding mode?

Note: this constraint probably implies not using the FPU at all. I expect the simplest way to do it in these conditions is to read the bits of the double in a 64-bit long and to work with that.

You can assume the endianness of your choice for simplicity, and that the double in question is available through the d field of the union below:

union double_bits
{
  long i;
  double d;
};

I would try to do it myself but I am certain I would introduce hard-to-notice bugs for denormalized or negative numbers.

+3  A: 

To do this job more accurately than just re-combine mantissa and exponent bit's check this out:

http://www.mathworks.com/matlabcentral/fileexchange/23173

regards

stacker
Thanks. The `doubles2halfp` function there is as complicated as I feared, but at least it already has half the constants right, so it's a good starting point.
Pascal Cuoq
stacker
+3  A: 
Alok
Thank you very much for this code. I was slowly becoming convinced that this was the least error-prone solution. Thanks for pointing out `nextafterf` too, that's much better than in/decrementing the bits of the `float` as if it was an `int`. To alleviate the risk of `f+1` being equal to `f`, may I write `nextafterf(f, INFINITY)` instead?
Pascal Cuoq
I just read the man pages, the C standard draft, and tried it out, and looks like `INFINITY` should work.
Alok
OK, I have edited my post. Thanks for the comment.
Alok