Code to convert characteristic.value to Int, in Swift

In my Objective-C code, this is how I used to convert the HR measurement value to bpm


    const uint8_t *reportData = [data bytes];
    uint16_t bpm = 0;
    if ((reportData[0] & 0x01) == 0) {
        /
        bpm = reportData[1];
    } else {
        /
        bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
    }

I probably picked up this from a sample code to one of the WWDC session.


How would you do this in Swift 3?

Currently,I'm going with this, not sure is it valid:


  var bpm: UInt8 = 0
  data.copyBytes(to: &bpm, count: sizeof(UInt8.self))

In the code above, there's some wrangling around UInt16, which I'm not sure what exactly it does.

Replies

Seeing your Objective-C code, I would write it in Swift 3 as:

    var bpm: UInt16 = 0
    data.withUnsafeBytes {(reportData: UnsafePointer<UInt8>)->Void in
        if reportData[0] & 0x01 == 0 {
            bpm = UInt16(reportData[1])
        } else {
            bpm = UInt16(littleEndian: UnsafePointer<UInt16>(reportData + 1).pointee)
        }
    }


Your Swift 3 code just reads the first byte in your `data`, which is used as a "size flag" (showing if `bpm` is a single byte data or two byte) in Objective-C code.