Pregunta

I am developing a portable class library in C# and I want to bit convert a double to a long. The most straightforward solution to this issue would be to use the BitConverter.DoubleToInt64Bits method, but unfortunately this method is not available in the Portable Library subset of the .NET class library.

As an alternative I have come up with the following "two-pass" bit conversion:

var result = BitConverter.ToInt64(BitConverter.GetBytes(x), 0);

My tests show that this expression consistently produces the same result as DoubleToInt64Bits. However, my benchmark tests also show that this alternative formulation is approximately four times slower than DoubleToInt64Bits when implemented in a full .NET Framework application.

Using only the Portable Library subset, is it possible to implement a replacement of DoubleToInt64Bits that is quicker than my formulation above?

¿Fue útil?

Solución

How about using a union?

[StructLayout(LayoutKind.Explicit)]
public struct DoubleLongUnion
{
    [FieldOffset(0)]
    public double Double;

    [FieldOffset(0)]
    public long Long;
}

public static long DoubleToInt64Bits(double value)
{
    var union = new DoubleLongUnion {Double = value};
    return union.Long;
}

Otros consejos

If you're able to flag your assembly as unsafe then you could just lift the DoubleToInt64Bits implementation into your own library:

public static unsafe long DoubleToInt64Bits(double value)
{
    return *(((long*) &value));
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top