문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top