gpt4 book ai didi

Swift BitConverter.DoubleToInt64Bits 等效

转载 作者:行者123 更新时间:2023-11-28 11:40:37 24 4
gpt4 key购买 nike

我需要 C# BitConverter.DoubleToInt64Bits(doubleValue) 的 Swift 实现。我发现网站上的 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 for ios 中的相同功能。像这样:

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

最佳答案

bitPattern Double 的属性返回具有相同内存表示的(无符号)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))

关于Swift BitConverter.DoubleToInt64Bits 等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com