swift - corebluetooth 写入 2 个字节

swift - corebluetooth writing 2 bytes

我正在获取文本输入并将其写入蓝牙设备。我对 1 字节的数据没有问题,但我无法将文本输入值转换为 2 字节并发送它。

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

对于 1 个字节,我使用:

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

我试过这样转换,但我无法发送带 .writeValue 的字符串:

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

您可能希望将字符串转换为 16 位整数,然后 将整数转换为数据(比较),最后将数据写入设备:

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, ...)