要使用Cocoa Touch解析带浮点数的二进制文件,您可以使用以下步骤:
import Foundation
func parseBinaryFile(url: URL) -> [Float]? {
do {
let data = try Data(contentsOf: url)
let floatSize = MemoryLayout<Float>.size
let count = data.count / floatSize
var floats = [Float](repeating: 0, count: count)
data.withUnsafeBytes { (rawBufferPointer) in
let bufferPointer = rawBufferPointer.bindMemory(to: Float.self)
for i in 0..<count {
floats[i] = bufferPointer[i]
}
}
return floats
} catch {
print("Error reading binary file: \(error)")
return nil
}
}
if let url = Bundle.main.url(forResource: "binary_file", withExtension: "bin") {
if let floats = parseBinaryFile(url: url) {
print("Floats: \(floats)")
}
}
这个函数将二进制文件转换为一个浮点数数组,并在控制台中打印出来。请注意,这个函数假设二进制文件中的数据是以原始字节格式存储的,并且每个浮点数都是4字节。如果您的二进制文件具有不同的格式,您可能需要修改此函数以适应您的需求。
领取专属 10元无门槛券
手把手带您无忧上云