我正在尝试与蓝牙激光标签枪进行通信,该枪以 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/