1

I am working a lot with Bluetooth, and most everything is designed to be a UInt8 which makes it very easy to encode/decode data streams:

    func encode() -> Data {
        let values: [UInt8] = [value1, value2]
        return Data(bytes: values)
    }

    init(data: Data) {
        let values = Array(data)
        self.value1 = values[0]
        self.value2 = values[1]
    }

But now I need to work with other data types. I have a related question on decoding, but now also need to encode and transmit Int16. My only thought was to use bit shifting/masking like so:

let x: Int16 = 21845
let x1 = UInt8(x >> 8)
let x2 = UInt8(x & 255)
let data = Data(bytes: [x2, x1])

Are there any cleaner methods like when working with UInt8 that don't involve using pointers and bit shifting? Preferably something that works for other data types too.

Community
  • 1
  • 1
jjatie
  • 4,229
  • 2
  • 28
  • 51
  • There are no pointers in your code. Bit shifting is a reasonable way of addressing this problem – Paulw11 Apr 03 '17 at 12:45

0 Answers0