简体   繁体   English

什么时候应该使用Double.longBitsToDouble(...)而不是简单地将long强制转换为double?

[英]When should I use Double.longBitsToDouble(…) instead of simply casting long to a double?

I have an array of double values where the last one will be in fact a long representing time in milliseconds. 我有一个双精度值数组,其中最后一个实际上是一个很长的表示时间(以毫秒为单位)。 Therefore this long needs to be converted to a double to fit into the array. 因此,需要将此long转换为double以适合数组。 Later at the time of retrieval of this long value it needs to be converted back to a long type. 稍后在检索此long值时,需要将其转换回long类型。 It is critical that the long value after retrieval from the array of doubles is exactly the same value (down to a one millisecond) I had before putting it into the array. 从double数组检索后的long值与将其放入数组之前的值完全相同(低至1毫秒),这一点至关重要。 There will be no operations whatsoever performed on the long value while in the array. 在数组中时,将不会对long值执行任何操作。 So the questions are: 所以问题是:
Should I simply cast the long value to double and upon retrieval cast it back to long? 我是否应该将long值简单地转换为double并在检索时将其转换回long? Will this preserve the exact value of my long? 这会保留我的多头头寸的确切价值吗?
Or should I use Double.longBitsToDouble(time) method to put the long into the array and retrieve it with Double.doubleToLongBits(time). 还是应该使用Double.longBitsToDouble(time)方法将long放入数组中,并使用Double.doubleToLongBits(time)进行检索。
Or maybe I should put the long value into the array using Double.longBitsToDouble(time) and retrieve the encoded long by simply casting it to long type? 还是我应该使用Double.longBitsToDouble(time)将long值放入数组中,并通过简单地将其强制转换为long类型来检索已编码的long?
Thank you in advance for your help. 预先感谢您的帮助。

I mean, what you should do is to not use an array to represent values meaning different things... 我的意思是,您应该做的是不要使用数组来表示表示不同含义的值...

But from what it sounds like, you have no choice but to use Double.longBitsToDouble , since a double cannot give you full precision on all long values. 但是从表面Double.longBitsToDouble ,您别无选择,只能使用Double.longBitsToDouble ,因为double精度不能为您提供所有long值的全精度。 Just casting a long to double will lose precision. 只是longdouble会丢失精度。

I would create a custom class that is basically a container for a double array and a single long value. 我将创建一个自定义类,该类基本上是double精度数组和单个long值的容器。 You should never use arrays for storing data of different types or with the intention of using certain elements of the array for different purposes. 绝对不要使用数组来存储不同类型的数据,也不要为了达到不同目的而使用数组的某些元素。

Example using a List<double> : 使用List<double>示例:

public class DoublesWithTimestampStructure
{
    private List<double> doubles;
    private long timestamp;

    public DoublesWithTimestampStructure()
    {
        this.doubles = new List<double>();
        this.timestamp = 0;
    }

    /*
    ... getter and setter methods, miscellaneous methods, etc.
    */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM