简体   繁体   English

Swift:从数据中提取Int16和Int8

[英]Swift: Extracting Int16 & Int8 from Data

I am trying to retrieve data from two BLE characteristics values. 我正在尝试从两个BLE特征值中检索数据。 They both contain structures, and I want to save this data as structures in my application too. 它们都包含结构,我也想将此数据另存为应用程序中的结构。 Data from first BLE characteristic is all Int16, I was able to save it. 来自第一个BLE特性的数据都是Int16,我能够保存它。 But the problem is that second characteristic contains both Int8 & Int16, and I can't find a solution to deal with it. 但是问题在于第二个特征同时包含Int8和Int16,而我找不到解决该问题的解决方案。

In my application, I have created two different structures for both characteristics. 在我的应用程序中,我为这两个特性创建了两个不同的结构。 The first structure looks like this, it's all Int16. 第一个结构看起来像这样,全都是Int16。

     struct FirstStruct {
     let a1: Int16
     ...
     let a6: Int16 }

The second is like that, has 2 types: 第二个就是这样,有两种类型:

     struct SecondStruct {
     let b1: Int16
     let b2: Int8
     let b3: Int8

} }

When I get data from characteristic.value for first characteristic, I am able to simply do it like this: 当我从第一个特征的feature.value获取数据时,我可以像这样简单地做到这一点:

    data = characteristic.value
    let firstData = data.withUnsafeBytes {(int16Ptr: UnsafePointer<Int16>)-> FirstStruct in
            FirstStruct(a1: Int16(littleEndian: int16Ptr[0]),
                        ...
                        a6: Int16(littleEndian: int16Ptr[5]))
        }

But how can I do it for the 2nd characteristic? 但是我该如何针对第二个特征呢? Same way doesn't work, because it has both Int16 & Int8, results in error. 同样的方法不起作用,因为它同时具有Int16和Int8,从而导致错误。 I guess, I could try to interpret all values as Int16 and then convert to Int8? 我想,我可以尝试将所有值解释为Int16,然后转换为Int8吗? But this is probably a bad idea? 但这可能是一个坏主意吗? Is there other way to extract the data from second characteristic and put it into my desired structure? 还有其他方法可以从第二个特征中提取数据并将其放入我想要的结构中吗?

May be this will help you: 可能这会帮助您:

let a:Int8 = 1
let b:Int16 = 1
let aSize = MemoryLayout.size(ofValue:a)
print(aSize) // will return 1
let bSize = MemoryLayout.size(ofValue:b)
print(bSize) // will return 2

Using this code, you can check the size of received values. 使用此代码,您可以检查接收值的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM