ios - 如何将 UInt8 数组转换为 Data? ( swift )

标签 ios arrays swift bluetooth binary

我正在尝试与蓝牙激光标签枪进行通信,该枪以 20 字节 block 的形式获取数据,这些数据被分解为 16、8 或 4 位字。为此,我创建了一个 UInt8 数组并更改了其中的值。当我尝试发送 UInt8 数组时出现问题。

            var bytes = [UInt8](repeating: 0, count: 20)
            bytes[0] = commandID
            if commandID == 240 {
                commandID = 0
            }
            commandID += commandIDIncrement
            
            print(commandID)
            bytes[2] = 128
            bytes[4] = UInt8(gunIDSlider.value)
            print("Response: \(laserTagGun.writeValue(bytes, for: gunCControl, type: CBCharacteristicWriteType.withResponse))")

commandID 只是一个 UInt8。这给了我错误,无法将类型“[UInt8]”的值转换为预期的参数类型“Data”,我试图通过这样做来解决这个问题:

var bytes = [UInt8](repeating: 0, count: 20)

    bytes[0] = commandID
    if commandID == 240 {
        commandID = 0
    }
    commandID += commandIDIncrement
    print(commandID)

    bytes[2] = 128
    bytes[4] = UInt8(gunIDSlider.value)
    print("bytes: \(bytes)")

    assert(bytes.count * MemoryLayout<UInt8>.stride >= MemoryLayout<Data>.size)
    let data1 = UnsafeRawPointer(bytes).assumingMemoryBound(to: Data.self).pointee
    print("data1: \(data1)")

    print("Response: \(laserTagGun.writeValue(data1, for: gunCControl, type: CBCharacteristicWriteType.withResponse))")
    

对此,data1 仅打印 0 字节,我可以看到 laserTagGun.writeValue 实际上并没有通过从其他特征读取数据来执行任何操作。如何快速将 UInt8 数组转换为 Data?另请告诉我是否有比 UInt8 数组更好的方法来处理 20 字节的数据。感谢您的帮助!

最佳答案

看起来您确实想避免字节的副本,如果不是,那么只需使用 bytes 数组初始化一个新数据即可:

let data2 = Data(bytes)
print("data2: \(data2)")

如果你真的想避免复制,像这样的东西怎么样?

let data1 = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: bytes.count, deallocator: .none)
print("data1: \(data1)")

关于ios - 如何将 UInt8 数组转换为 Data? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62904588/

相关文章:

ios - swift 3 : UIViewControllerTransitioningDelegate stopped working

ios - Xamarin 单元测试不会加载到模拟器或手机 : "Cannot register two managed types ... with the same native name (' AppDelegate').“

JavaScript 运算符 "in"

ios - 基于Notification有效负载快速显示Viewcontroller

ios - 加载所有内容后如何更改uitableview单元格的字体大小

ios - 在 iOS 中是否可以使用没有访问 token 的用户 ID 来获取用户的好友列表?

php - 按月对数据进行分组,并使用 Symfony2、Twig 和 Flot.js 将其显示在多维数组中

java - 是否有类似于 ArrayList 的 Java 类可以做到这一点?

swift - 如何使 View Controller 扩展以适应较小屏幕上的布局?

iOS Core Plot with Swift - 格式化 Axis