Reputation: 13830
My question is similar to this question which deals with positive floating point values.
In my case, I'm dealing with both positive and negative float
values, and want to store it in an int64_t
type.
NOTE: I wish to use memcpy
rather than relying on a union (which is UB in C++).
Upvotes: 1
Views: 540
Reputation: 215287
As described in my comment on the linked question about a 32-bit variant:
...basically you can either use a signed int32 and invert the low 31 bits if the sign bit is set. A similar approach works if you want unsigned but you have to add the 0x80000000 bias.
As code, adapted to 64-bit:
int64_t order_preserving_repr(double x)
{
int64_t k;
memcpy(&k, &x, sizeof k);
if (k<0) k ^= INT64_MAX;
return k;
}
Upvotes: 2