本文介绍了在 Swift 中将字节数组转换为双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Swift 中将字节数组转换为双精度值?
How can one convert an array of bytes into a double value in Swift?
(这是一个 NSInputStream 扩展)
(It's an NSInputStream extension)
我的代码片段附在下面,但它没有返回正确的双精度值:
My snippet attached below, but it's not returning correct double value:
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 中的任何浮点类型.
This code does work for any floating point type in Swift.
macOS 上的 Swift 3.0(little-endian 表示 Double
)
您可以在此处查找我的备忘单以进行字节转换.(小/大端数字转换)
You can look up my cheat sheet for byte conversion here. (little/big endian number conversion)
这篇关于在 Swift 中将字节数组转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!