ios - 在 Swift for Mac 上,BLE 的数据类型转换

标签 ios swift macos bluetooth-lowenergy core-bluetooth

我有一个问题。我正在尝试与 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")
    } 


}

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

最佳答案

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

characteristic.value!.bytes

但是返回类型.bytesUnsafePointer<Void> ,然后将其转换为 UnsafePointer<Int32>类型,在 Swift 中相当于指向 32 位整数 ( int32_t* ptr; ) 的 C 指针。

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

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

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

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

关于ios - 在 Swift for Mac 上,BLE 的数据类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158482/

相关文章:

ios - FCM ios 配置

c - setjmp/signal 崩溃异常处理

IOS:如何将 NSArray 转换为 NSIndexPath

iphone - iOS Keychain 偶尔会返回空字符串

ios - 在 Objective C 类中使用 Swift 类和 swift 项目

objective-c - CAShapeLayer 类创建

xcode - 在 OS X 10.11 上构建静态 libcurl.a,但找不到 libcurl.a

objective-c - OSX - 从缩放按钮禁用全屏模式?

ios - iOS中不同位置的商店数据库有什么区别?

ios - 动画期间无法获取 CALayer 的当前位置