在保留顺序的同时将float转换为int64_t [英] Convert float to int64_t while preserving ordering

查看:120
本文介绍了在保留顺序的同时将float转换为int64_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题类似于此问题处理正浮点值.

My question is similar to this question which deals with positive floating point values.

就我而言,我正在处理正和负float值,并希望将其存储为int64_t类型.

In my case, I'm dealing with both positive and negative float values, and want to store it in an int64_t type.

注意:我希望使用memcpy而不是依靠联合(在C ++中是UB).

NOTE: I wish to use memcpy rather than relying on a union (which is UB in C++).

推荐答案

正如我对有关32位变体的链接问题的评论中所述:

As described in my comment on the linked question about a 32-bit variant:

...基本上,如果设置了符号位,则可以使用带符号的int32并反转低31位.如果您想要无符号,但必须添加0x80000000偏差,则可以使用类似的方法.

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

作为代码,适用于64位:

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

这篇关于在保留顺序的同时将float转换为int64_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆