简体   繁体   English

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

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

I am trying to communicate with a Bluetooth laser tag gun that takes data in 20 byte chunks, which are broken down into 16, 8 or 4-bit words.我正在尝试与蓝牙激光标签枪通信,它以 20 字节块的形式获取数据,这些数据被分解为 16、8 或 4 位字。 To do this, I made a UInt8 array and changed the values in there.为此,我创建了一个 UInt8 数组并更改了其中的值。 The problem happens when I try to send the UInt8 array.当我尝试发送 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 is just a UInt8. commandID 只是一个 UInt8。 This gives me the error, Cannot convert value of type '[UInt8]' to expected argument type 'Data' , which I tried to solve by doing this:这给了我错误, 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))")
    

To this, data1 just prints 0 bytes and I can see that laserTagGun.writeValue isn't actually doing anything by reading data from the other characteristics.为此, data1 只打印0 bytes ,我可以看到laserTagGun.writeValue实际上并没有通过从其他特征读取数据来做任何事情。 How can I convert my UInt8 array to Data in swift?如何将我的 UInt8 数组转换为 swift 中的数据? Also please let me know if there is a better way to handle 20 bytes of data than a UInt8 array.另外请让我知道是否有比 UInt8 数组更好的方法来处理 20 字节的数据。 Thank you for your help!谢谢您的帮助!

It looks like you're really trying to avoid a copy of the bytes, if not, then just init a new Data with your bytes array:看起来你真的想避免字节的副本,如果没有,那么只需用你的bytes数组初始化一个新的数据:

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

If you really want to avoid the copy, what about something like this?如果你真的想避免复制,那么这样的事情呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM