Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Portable library missing BitConverter.DoubleToInt64Bits, replacement very slow

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?

like image 975
Anders Gustafsson Avatar asked May 09 '12 13:05

Anders Gustafsson


2 Answers

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;
}
like image 182
Omer Mor Avatar answered Nov 01 '22 13:11

Omer Mor


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));
}
like image 22
Sean Avatar answered Nov 01 '22 12:11

Sean