在Swift中从二进制文件读取整数

3

我有一个二进制文件,代表着一张旧的打孔卡片。该文件包含以下数据:

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)

这个模式将以不同的值重复约100,000次,并表示具有机器功能的2D CAD设计。

文件/冲孔卡的每一行都有5个字节(1个Uint8,2个int16)。最好的读取方法是什么? 在C#中,我使用流逐个读取字节,但我找不到Swift 5的示例。

1个回答

8
您可以使用这样的函数打开二进制文件(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
    }
}

使用方法:

if let bytes: [UInt8] = getFile(forResource: "foo", withExtension: "json") {
    for byte in bytes {
        // Process single byte...
    }
}

然后只需要遍历这些字节,并按照您的要求进行格式化。


谢谢,这正是我在寻找的。只需要在使用部分进行一点更改。您写的 fileExt: "json" 需要改为 withExtension: "json",Xcode 会提示您更改。 - Andreas Pircher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接