arrays - 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"
解决方案
您可能希望将字符串转换为 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, ...)
推荐阅读
- java - 从列表视图到 PDF 的数据
- python - 如何让 h2o 以非科学计数法返回结果
- c# - C# Socket 异常 - 无法建立连接,因为目标机器主动拒绝它
- javascript - “消息”错误:“禁止”尝试查询 Apollo Serverless Lambda 服务器
- c# - 有没有办法制作动态模型?
- javascript - 为什么这张图片没有旋转?
- kubernetes - 在具有固定域和端口的 GKE 中运行可扩展服务
- angular - 尽管从服务调用收集的产品显示在页面上,但接口日志未定义
- unix - 制作以破折号开头的 grep 搜索模式
- php - 使用 CodeIgniter 上传多个文件 - 偏移错误