Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] {
    //...
}
like image 825
vkalit Avatar asked Nov 19 '15 20:11

vkalit


2 Answers

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.

let url = URL(fileURLWithPath: "myTestFile.myBinExt")

// Writing
var wArray: [Float] = [1.1, 3.7, 2.5, 6.4, 7.8]
let wData = Data(bytes: &wArray, count: wArray.count * MemoryLayout<Float>.stride)
try! wData.write(to: url)

// Reading file
let rData = try! Data(contentsOf: url)

// Converting data, version 1
var rArray: [Float]?

rData.withUnsafeBytes { (bytes: UnsafePointer<Float>) in
    rArray = Array(UnsafeBufferPointer(start: bytes, count: rData.count / MemoryLayout<Float>.size))
}

print(rArray!)

// Converting data, version 2
let tPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rData.count)
rData.copyBytes(to: tPointer, count: rData.count)

defer {
    tPointer.deinitialize(count: rData.count)
    tPointer.deallocate(capacity: rData.count)
}

var pointer = UnsafeRawPointer(tPointer) // Performs no allocation or copying; no deallocation shall be done.

// MemoryLayout<Float>.size = 4
print(pointer.load(fromByteOffset: 00, as: Float.self))
print(pointer.load(fromByteOffset: 04, as: Float.self))
print(pointer.load(fromByteOffset: 08, as: Float.self))
print(pointer.load(fromByteOffset: 12, as: Float.self))
print(pointer.load(fromByteOffset: 16, as: Float.self))

Output:

[1.10000002, 3.70000005, 2.5, 6.4000001, 7.80000019]
1.1
3.7
2.5
6.4
7.8
like image 131
Andreas detests censorship Avatar answered Oct 23 '22 13:10

Andreas detests censorship


Please try this...

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

func writeArrayToPlist(array: [Float]) {
    if let arrayPath: String = createArrayPath() {
        (array as NSArray).writeToFile(arrayPath, atomically: false)
    }
}

func readArrayFromPlist() -> [Float]? {
    if let arrayPath: String = createArrayPath() {
        if let arrayFromFile: [Float] = NSArray(contentsOfFile: arrayPath) as? [Float] {
            return arrayFromFile
        }
    }
    return nil
}

func createArrayPath () -> String? {
    if let docsPath: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last {
        return ((docsPath as NSString).stringByAppendingPathComponent("myArrayFileName") as NSString).stringByAppendingPathExtension("plist")
    }
    return nil
}
like image 24
Dennis Weidmann Avatar answered Oct 23 '22 12:10

Dennis Weidmann