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

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

As an alternative, I came 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 benchmarks also show that this alternative formulation is about four times slower than DoubleToInt64Bits when it is implemented in the full .NET Framework application.

Using only a subset of the Portable Library, is it possible to implement the DoubleToInt64Bits replacement, which is faster than my wording above?

+6
source share
2 answers

How about using 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; } 
+5
source

If you can specify your assembly as unsafe , you can simply raise the implementation of DoubleToInt64Bits to your own library:

 public static unsafe long DoubleToInt64Bits(double value) { return *(((long*) &value)); } 
+3
source

Source: https://habr.com/ru/post/915287/


All Articles