gpt4 book ai didi

ios - 将 Float 数组写入二进制文件并快速读取

转载 作者:可可西里 更新时间:2023-10-31 23:58:01 25 4
gpt4 key购买 nike

如何将Float数组写入二进制文件,然后读取它?

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

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

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

最佳答案

正如您在评论中所说,速度是重中之重。然后,我建议您使用 Cocoa 提供的 Data 类将数组写入二进制文件(如最初要求的那样)。

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))

输出:

[1.10000002, 3.70000005, 2.5, 6.4000001, 7.80000019]
1.1
3.7
2.5
6.4
7.8

关于ios - 将 Float 数组写入二进制文件并快速读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com