And*_*her 3 arrays byte file swift
我有一个代表旧打孔卡的二进制文件。该文件有以下数据:
Function(unsigned int8 min: 0, max: +255),
Vertical Movement (signed int16 min: -32.768, max: +32.767)
Horizontal Movement (signed int16 min: -32.768, max: +32.767)
Run Code Online (Sandbox Code Playgroud)
此模式将使用不同的值重复大约。100.000 次,将代表具有机器功能的 2D CAD 设计。
文件/打孔卡的每一行都有 5 个字节(1 x Uint8、2 x int16)。最好的阅读方式是什么?在 C# 中,我使用流来读取一个又一个字节,但我找不到在 Swift 5 中执行此操作的示例。
您可以使用如下函数打开二进制文件(Swift 5):
func getFile(forResource resource: String, withExtension fileExt: String?) -> [UInt8]? {
// See if the file exists.
guard let fileUrl: URL = Bundle.main.url(forResource: resource, withExtension: fileExt) else {
return nil
}
do {
// Get the raw data from the file.
let rawData: Data = try Data(contentsOf: fileUrl)
// Return the raw data as an array of bytes.
return [UInt8](rawData)
} catch {
// Couldn't read the file.
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
if let bytes: [UInt8] = getFile(forResource: "foo", withExtension: "json") {
for byte in bytes {
// Process single byte...
}
}
Run Code Online (Sandbox Code Playgroud)
然后简单地迭代字节并将它们格式化为您的规范。