首页 > 解决方案 > swift - corebluetooth 写入 2 个字节

问题描述

我得到一个文本输入并将其写入 ble 设备。我对 1 个字节的数据没有问题,但我无法将文本输入值转换为 2 个字节并发送它。

如何将 3400 之类的值转换为 UInt8 数组的 2 个字节,对于 255 以下的值我应该怎么做?

对于 1 个字节,我使用:

let myInt = Int(textField.text)
let value: [UInt8] = [UInt8(myInt)]
self.bluetoothManager.writeValue(data: Data(bytes: value), forCharacteristic: myChar!, type: .withResponse)

我尝试像这样进行转换,但无法使用 .writeValue 发送字符串:

https://stackoverflow.com/a/36967037/4704055

   let d1 = 21
   let b1 = String(d1, radix: 2) 
   print(b1) // "10101"

标签: arraysswiftbytecore-bluetooth

解决方案


您可能希望将字符串转换为 16 位整数,然后将整数转换为数据(比较往返 Swift 数字类型与 Data 之间的比较),最后将数据写入设备:

guard var value = Int16(textField.text) else {
    // ... invalid number ...
}
// value = value.bigEndian (if big-endian is expected by the device)
let data = Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
self.bluetoothManager.writeValue(data: data, ...)

推荐阅读