swift-corebluetooth写2个字节 [英] swift - corebluetooth writing 2 bytes

查看:54
本文介绍了swift-corebluetooth写2个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

对于1个字节,我使用:

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)

我尝试过这样的转换,但无法使用.writeValue发送String:

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"

推荐答案

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

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

这篇关于swift-corebluetooth写2个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆