我的问题类似于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/