jjatie jjatie - 1 month ago 14
Objective-C Question

How to extract Int16 from Data in Swift 3

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.

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;
}


to Swift 3?

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

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


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)

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

Answer

Try using 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
Comments