gpt4 book ai didi

swift - 在 Swift 中将字节数组转换为 double

转载 作者:行者123 更新时间:2023-11-30 14:10:56 25 4
gpt4 key购买 nike

如何在 Swift 中将字节数组转换为 double 值?

(这是一个 NSInputStream 扩展)

我的代码片段附在下面,但它没有返回正确的 double 值:

func readDouble() -> Double
{
var readBuffer = Array<UInt8>(count:sizeof(Double), repeatedValue: 0)

let numberOfBytesRead = self.read(&readBuffer, maxLength: readBuffer.count)
let help1 = Int(readBuffer[0] & 0xff) << 56 | Int(readBuffer[1] & 0xff) << 48
let help2 = Int(readBuffer[2] & 0xff) << 40 | Int(readBuffer[3] & 0xff) << 32
let help3 = Int(readBuffer[4] & 0xff) << 24 | Int(readBuffer[5] & 0xff) << 16
let help4 = (Int(readBuffer[6] & 0xff) << 8) | Int(readBuffer[7] & 0xff)
return Double(help1 | help2 | help3 | help4)
}

最佳答案

很简单:

extension FloatingPoint {

init?(_ bytes: [UInt8]) {

guard bytes.count == MemoryLayout<Self>.size else { return nil }

self = bytes.withUnsafeBytes {

return $0.load(fromByteOffset: 0, as: Self.self)
}
}
}

let array: [UInt8] = [0, 0, 0, 0, 0, 0, 240, 63]
let num = Double(array) // 1.0

此代码适用于 Swift 中的任何浮点类型。

ma​​cOS 上的 Swift 3.0(Doublelittle-endian 表示)

您可以查找我的字节转换备忘单 here 。 (小/大端数转换)

关于swift - 在 Swift 中将字节数组转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773367/

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