From 2fd5f6aaac631379f6e4370b1dd5fd1932263022 Mon Sep 17 00:00:00 2001 From: Christoph Ruegg Date: Sat, 14 Jul 2012 14:03:48 +0200 Subject: [PATCH] Portable: Union for better double-long conversion perf --- src/Numerics/Precision.cs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Numerics/Precision.cs b/src/Numerics/Precision.cs index 4880e7ec..bc131b87 100644 --- a/src/Numerics/Precision.cs +++ b/src/Numerics/Precision.cs @@ -34,6 +34,10 @@ namespace MathNet.Numerics using System.Collections.Generic; using System.Numerics; +#if PORTABLE + using System.Runtime.InteropServices; +#endif + /// /// Utilities for working with floating point numbers. /// @@ -1822,17 +1826,30 @@ namespace MathNet.Numerics #if PORTABLE internal static long DoubleToInt64Bits(double value) { - return BitConverter.ToInt64(BitConverter.GetBytes(value), 0); + var union = new DoubleLongUnion {Double = value}; + return union.Int64; } internal static double Int64BitsToDouble(long value) { - return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); + var union = new DoubleLongUnion {Int64 = value}; + return union.Double; } - internal static double Truncate(double value){ + internal static double Truncate(double value) + { return value >= 0.0 ? Math.Floor(value) : Math.Ceiling(value); } + + [StructLayout(LayoutKind.Explicit)] + public struct DoubleLongUnion + { + [FieldOffset(0)] + public double Double; + + [FieldOffset(0)] + public long Int64; + } #endif } } \ No newline at end of file