a way to specily floating-point numbers as bit patters

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 9 09:07:36 PDT 2017


let's say that i have precomputed some `float`-typed tables, and now i want 
to use 'em in my code. for example, a table for Lagrange series. the table 
itself is like 10 numbers, but the code calculating it rather big, and it 
depends of architecture (so it can yield different results on different 
arch). yet i want the same IEEE numbers everywhere.

the code problem is that i really can't express *exactly* *the* *same* IEEE float 
with D. let me illustrate this.

one of my calculated values is `-0.166667`, which has bit-pattern of 0xBE2AAAB7.
now, let's say i want to use this number in my code:

	float v = -0.166667f;
	writefln("%f 0x%08X", v, *cast(uint*)&v);

oooops. "-0.166667 0xBE2AAAC1". it's not the same! (and yes, it matters).

and this means that i can't inline my calculated values! each time i want 
to get floating value with a known bit-pattern, i have to store it as uint, 
and resort to ugly hack: `*cast(immutable(float)*)(&mytable[2])`.

and i can't do this trick in CTFE, as such pointer tricks aren't permitted.

i tried different workarounds, but they're all ugly. it would be very nice 
to have a way to define IEEE floating point numbers as bit-patterns in the 
language itself. what do you think?

yes, i know that floating numbers has to be loaded from memory anyway, so 
my trick is not really worse than specifying the constant directly. but it 
is still dirty trick, and i cannot use it in @safe code too, so i have to 
mark my code as @trusted, which is not the same at all. there probably may 
be other trick such this for @safe code, but... you got the idea, i think.


More information about the Digitalmars-d-learn mailing list