Swift BitConverter.DoubleToInt64Bits 等效

Swift BitConverter.DoubleToInt64Bits Equivalent

我需要 Swift C# BitConverter.DoubleToInt64Bits(doubleValue) 的实现。 我发现网站上的 C# 实现只有

https://referencesource.microsoft.com/#mscorlib/system/bitconverter.cs

 [SecuritySafeCritical]
    public static unsafe long DoubleToInt64Bits(double value) {
        /// some comments ....
        Contract.Assert(IsLittleEndian, "This method is implemented assuming little endian with an ambiguous spec.");
        return *((long *)&value);
    }

在 c# 中我有方法:

public long EncodeValue(double doubleValue)
{
    return BitConverter.DoubleToInt64Bits(doubleValue);
}

但我需要在 Swift 中为 ios 提供相同的功能。 像这样:

func EncodeValue(doubleValue: Double)
{
    return SwiftDoubleToInt64Bits(doubleValue)
}

Double returns 的 bitPattern 属性 具有相同内存表示的(无符号)64 位整数:

let doubleValue = 12.34
let encoded = doubleValue.bitPattern // UInt64

反向转换是用

完成的
let decoded = Double(bitPattern: encoded)
print(decoded) // 12.34

您可以用同样的方式在 FloatUInt32 之间转换。

对于平台无关的内存表示(例如“big endian”)使用

let encodedBE = doubleValue.bitPattern.bigEndian
let decoded = Double(bitPattern: UInt64(bigEndian: encodedBE))