c# – .NET可移植库缺少BitConverter.DoubleToInt64Bits,替换速度很慢

前端之家收集整理的这篇文章主要介绍了c# – .NET可移植库缺少BitConverter.DoubleToInt64Bits,替换速度很慢前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在用C#开发一个可移植的类库,我希望将double转换为long.这个问题最直接的解决方案是使用BitConverter.DoubleToInt64Bits方法,但不幸的是,这个方法在.NET类库的Portable Library子集中不可用.

作为替代方案,我提出了以下“双通”位转换:

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

我的测试表明,这个表达式始终产生与DoubleToInt64Bits相同的结果.但是,我的基准测试还表明,在完整的.NET Framework应用程序中实现时,此替代公式比DoubleToInt64Bits慢大约四倍.

仅使用可移植库子集,是否可以实现比上面的公式更快的DoubleToInt64Bits替换?

解决方法

使用工会怎么样?
[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;
}
原文链接:https://www.f2er.com/csharp/91807.html

猜你在找的C#相关文章