c++ - 在保留顺序的同时将float转换为int64_t

标签 c++ floating-point x86-64

我的问题类似于this question,它处理正浮点值。

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

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

最佳答案

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

...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位:
int64_t order_preserving_repr(double x)
{
    int64_t k;
    memcpy(&k, &x, sizeof k);
    if (k<0) k ^= INT64_MAX;
    return k;
}

关于c++ - 在保留顺序的同时将float转换为int64_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60530255/

相关文章:

mysql - 在 mysql 中存储大型 float 据数组以便通过 django 访问的最有效方法是什么?

c - 使用 GCC 内联汇编的 PC 相关调用

assembly - fs和gs寄存器如何计算有效地址

c++ - 如何在单个声明中设置继承的 C++ 类/结构变量

c++ - 在什么情况下,您在 C++ 中使用信号量而不是互斥量?

c++ - 声明后初始化 C++ 模板类

C++ 静态属性

c++ - 如何编写类层次结构以在浮点类型之间轻松切换?

objective-c - 比较浮点值有多危险?

linux - 在 x86 (32bit) Linux 上启动 x86_64 代码,在 x86_64 CPU 上运行