Home:ALL Converter>Write array of Float to binary file and read it in swift

Write array of Float to binary file and read it in swift

Ask Time:2015-11-20T04:30:55         Author:vkalit

Json Formatter

How can I write array of Floatto binary file and then read it?

var array: [Float]: [0.1, 0.2, 0.3]

func writeArrayToBinary(array: [Float]) {
    //...
}

func readArrayFromBinary() -> [Float] {
    //...
}

Author:vkalit,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/33813812/write-array-of-float-to-binary-file-and-read-it-in-swift
Andreas detests censorship :

As you stated in a comment, speed is priority. Then, I suggest you write your array to a binary file (as originally requested), using the Data class, provided with Cocoa.\nlet url = URL(fileURLWithPath: "myTestFile.myBinExt")\n\n// Writing\nvar wArray: [Float] = [1.1, 3.7, 2.5, 6.4, 7.8]\nlet wData = Data(bytes: &wArray, count: wArray.count * MemoryLayout<Float>.stride)\ntry! wData.write(to: url)\n\n// Reading file\nlet rData = try! Data(contentsOf: url)\n\n// Converting data, version 1\nvar rArray: [Float]?\n\nrData.withUnsafeBytes { (bytes: UnsafePointer<Float>) in\n rArray = Array(UnsafeBufferPointer(start: bytes, count: rData.count / MemoryLayout<Float>.size))\n}\n\nprint(rArray!)\n\n// Converting data, version 2\nlet tPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rData.count)\nrData.copyBytes(to: tPointer, count: rData.count)\n\ndefer {\n tPointer.deinitialize(count: rData.count)\n tPointer.deallocate(capacity: rData.count)\n}\n\nvar pointer = UnsafeRawPointer(tPointer) // Performs no allocation or copying; no deallocation shall be done.\n\n// MemoryLayout<Float>.size = 4\nprint(pointer.load(fromByteOffset: 00, as: Float.self))\nprint(pointer.load(fromByteOffset: 04, as: Float.self))\nprint(pointer.load(fromByteOffset: 08, as: Float.self))\nprint(pointer.load(fromByteOffset: 12, as: Float.self))\nprint(pointer.load(fromByteOffset: 16, as: Float.self))\n\nOutput:\n[1.10000002, 3.70000005, 2.5, 6.4000001, 7.80000019]\n1.1\n3.7\n2.5\n6.4\n7.8\n",
2018-02-07T00:45:34
yy