swift - corebluetooth writing 2 bytes

感情迁移 提交于 2021-02-08 11:35:50

问题


I getting a text input and writing it to a ble device. I don't have an issue for 1 Byte of data but I could not covert the text input value to 2 bytes and send it.

How can I convert a value like 3400 to 2 bytes of UInt8 array and what should I for values below 255?

For 1 byte I use:

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

I tried to convert like this but I can't send String with .writeValue:

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

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

回答1:


You probably want to convert the string to a 16-bit integer, then convert the integer to data (compare round trip Swift number types to/from Data), and finally write the data to the device:

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


来源:https://stackoverflow.com/questions/51865737/swift-corebluetooth-writing-2-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!