0

How would I convert this properly? the value I need is byte number 0-1, has a format of uint16 and its units are in degrees.

print("derived : \(characteristic.value!)")
print(String(bytes: characteristic.value!, encoding: .utf16))

derived : 20 bytes
Optional("\0{Ͽ⌜ƀ")
  • 1
    See [round trip Swift number types to/from Data](https://stackoverflow.com/questions/38023838/round-trip-swift-number-types-to-from-data) – rmaddy May 30 '19 at 20:30

1 Answers1

0

You just need to get the first two bytes of the Data as UInt16.

var result: UInt16 = 0
_ = withUnsafeMutableBytes(of: &result) {characteristic.value!.copyBytes(to: $0, from: 0...1)}
print("\(result) degrees")

Assuming your format of uint16 is in Little-Endian as well as iOS, which is more often found in BLE characteristics.

(When you get the first value in Data, from: 0...1 is not needed, but you may want some data in other position.)

OOPer
  • 44,179
  • 5
  • 90
  • 123