【问题标题】:Read integers from binary file in Swift在 Swift 中从二进制文件中读取整数
【发布时间】:2019-11-25 16:50:25
【问题描述】:

我有一个代表旧打孔卡的二进制文件。该文件有以下数据:

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 x Uint8, 2 x int16)。阅读它的最佳方式是什么? 在 C# 中,我使用流来读取一个接一个字节,但在 Swift 5 中找不到示例。

【问题讨论】:

    标签: arrays swift file byte


    【解决方案1】:

    您可以使用这样的函数(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", fileExt: "json") {
        for byte in bytes {
            // Process single byte...
        }
    }
    

    然后简单地遍历字节并将它们格式化为您的规范。

    【讨论】:

    • 谢谢,这正是我想要的。它只需要在使用部分稍作改动。你在哪里写fileExt: "json" Xcode 告诉你把它改成withExtension: "json"
    猜你喜欢
    • 2010-11-12
    • 2016-11-13
    • 2011-09-02
    • 2015-11-11
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多