问题
How can one convert an array of bytes into a double value in Swift?
(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)
}
回答1:
My understanding is that your byte array is a serialization of the binary representation. However, the Double
constructor you're using takes an integer value and returns a corresponding Double
. Double(3)
returns 3.0
.
The right constructor would probably be Double(_bits:)
, but it accepts a Builtin.FPIEEE64
and it looks like its availability is an implementation detail. You should probably consider making a C function and bridge it to Swift.
回答2:
It's very simple:
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
This code does work for any floating point type in Swift.
Swift 3.0 on macOS (little-endian representation of Double
)
You can look up my cheat sheet for byte conversion here. (little/big endian number conversion)
来源:https://stackoverflow.com/questions/31773367/convert-byte-array-to-double-in-swift