如何将我的 UInt8 数组转换为数据? (Swift)

How can I convert my UInt8 array to Data? (Swift)

我正在尝试与蓝牙激光标签枪通信,该枪以 20 字节块的形式获取数据,这些块被分解为 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。这给了我错误,Cannot convert value of type '[UInt8]' to expected argument type '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 bytes,我可以看到 laserTagGun.writeValue 实际上并没有通过从其他特征读取数据来做任何事情。如何将我的 UInt8 数组转换为 swift 中的数据?另外请让我知道是否有比 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)")