【问题标题】:On Swift for Mac, data type conversion for BLE在 Swift for Mac 上,BLE 的数据类型转换
【发布时间】:2016-07-02 09:13:07
【问题描述】:

我有一个问题。我正在尝试与 Mi Band 交互。在 github 上找到了这段代码,它运行良好。但是我不明白数据类型转换发生了什么。

            var u16 = UnsafePointer<Int32>(characteristic.value!.bytes).memory

来自这个代码块:

    func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

    output("Data for "+characteristic.UUID.UUIDString, data: characteristic.value!)

    if(characteristic.UUID.UUIDString == "FF06") {
        spinnerView.hidden = true
        let u16 = UnsafePointer<Int>(characteristic.value!.bytes).memory
        stepsView.stringValue = ("\(u16) steps")
    } else if(characteristic.UUID.UUIDString == "FF0C") {
        spinnerView.hidden = true
        var u16 = UnsafePointer<Int32>(characteristic.value!.bytes).memory
        u16 =  u16 & 0xff
        batteryView.stringValue = ("\(u16) % charged")
    } 


}

谁能给我解释一下?谢谢!

【问题讨论】:

  • 这是一种将 NSData 转换为其他值(在我们的例子中,它们是 intInt32)的方法(或最新版本的 Swift 中的新方法,我不知道)。之前是getBytes:length:
  • @Larme 感谢您的回复。在那种情况下,为什么要使用“UnsafePointer”?

标签: ios swift macos bluetooth-lowenergy core-bluetooth


【解决方案1】:

这部分获取内存中的地址:

characteristic.value!.bytes

但是.bytes 的返回类型是UnsafePointer&lt;Void&gt;,因此它随后被转换为UnsafePointer&lt;Int32&gt; 类型,它相当于一个指向32 位整数(int32_t* ptr;) 的C 指针的Swift。

UnsafePointer<Int32>(characteristic.value!.bytes)

在 Swift 中,您使用 .memory 获取此类指针的内容(在 C 中为 *ptr)。所以u16 变量是Int32 类型的值(该内存位置的内容,解释为Int32)。

var u16 = UnsafePointer<Int32>(characteristic.value!.bytes).memory

接下来的几行屏蔽掉所有高 24 位,只留下值的最低有效 8 位,然后将其打印为电池百分比。

【讨论】:

    【解决方案2】:

    斯威夫特 3

      if you have this kind of characteristic :
    
     <CBCharacteristic: 0x26e42b42, UUID = Battery, properties = 0x33, 
      value = <4d455348 54454348 204153>, notifying = NO>
    
    
      then use this type code:
      let value = [UInt8](characteristic.value!)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      相关资源
      最近更新 更多