【问题标题】:How can I convert my UInt8 array to Data? (Swift)如何将我的 UInt8 数组转换为数据? (迅速)
【发布时间】:2020-11-04 08:16:47
【问题描述】:

我正在尝试与蓝牙激光标签枪进行通信,该枪以 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 数组转换为 Data?另外请让我知道是否有比 UInt8 数组更好的方法来处理 20 字节的数据。感谢您的帮助!

【问题讨论】:

  • 你想避免复制吗?

标签: ios arrays swift bluetooth binary


【解决方案1】:

看起来您确实在尝试避免复制字节,如果没有,那么只需使用您的 bytes 数组初始化一个新数据:

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

如果你真的想避免复制,那么这样的事情呢?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 2012-01-08
    • 2019-04-04
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    相关资源
    最近更新 更多