Convert float to int64_t while preserving ordering

喜夏-厌秋 提交于 2020-05-13 23:39:32

问题


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++).


回答1:


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;
}


来源:https://stackoverflow.com/questions/60530255/convert-float-to-int64-t-while-preserving-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!