如何在 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 中的任何浮点类型。
macOS 上的 Swift 3.0(Double
的little-endian 表示)
您可以查找我的字节转换备忘单 here 。 (小/大端数转换)
关于swift - 在 Swift 中将字节数组转换为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773367/