如何在 Swift 3 中从数据中提取 Int16 [英] How to extract Int16 from Data in Swift 3

查看:53
本文介绍了如何在 Swift 3 中从数据中提取 Int16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天以来,我一直在尝试访问 BLE 服务特征值中的数据.我想弄清楚如何翻译 温度传感器 示例Swift 会有所帮助,但我会卡在同一个地方.

I've been trying to access the data in a BLE service characteristic value for a few days now. I thought figuring out how to translate the Temperature Sensor example to Swift would be helpful, but I get stuck at the same spot.

我如何翻译 Obj-C:

How do I translate the Obj-C:

- (CGFloat) maximumTemperature
{
    CGFloat result  = NAN;
    int16_t value   = 0;

    if (maxTemperatureCharacteristic) {
        [[maxTemperatureCharacteristic value] getBytes:&value length:sizeof (value)];
        result = (CGFloat)value / 10.0f;
    }
    return result;
}

到 Swift 3?

在我的代码中,我使用的是结构体,而不是 CGFloat:

Instead of a CGFloat, in my code I am using the struct:

struct MPUData {
    let x: Int16
    let y: Int16
    let z: Int16
}

并且我从特征中接收到一个 8 字节的值,其中前六个是 x、y 和 z 分量(即 0x0D0E0F00 其中 x = 0x0D, y = 0x0E, z = 0x0F 最后一个字节未使用)

and am receiving an 8 byte value from the characteristic with the first six being the x, y, and z components (i.e 0x0D0E0F00 where x = 0x0D, y = 0x0E, z = 0x0F and the last byte is unused)

我不知道如何遍历这些位并将它们存储为它们的 Int16 值.任何帮助将不胜感激.

I have no idea how to traverse the bits and store them as their Int16 values. Any help would be greatly appreciated.

推荐答案

尝试使用 withUnsafeBytes:

//Assuming `data` as `someCharacteristic.value!`
//Create 4 Int16 data in little endian
let data = Data(bytes: [0x0D, 0, 0x0E, 0, 0x0F, 0, 0, 0])

struct MPUData {
    let x: Int16
    let y: Int16
    let z: Int16
}
let mpuData = data.withUnsafeBytes {(int16Ptr: UnsafePointer<Int16>)->MPUData in
    MPUData(x: Int16(littleEndian: int16Ptr[0]),
        y: Int16(littleEndian: int16Ptr[1]),
        z: Int16(littleEndian: int16Ptr[2]))
}
print(mpuData.x,mpuData.y,mpuData.z) //->13 14 15

这篇关于如何在 Swift 3 中从数据中提取 Int16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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