6

How to convert Data to array of UInt8?

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
print("recieved:\(data)")
let arr: [UInt8] = Data(???)???
}

log recieved:70 bytes

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
AleyRobotics
  • 960
  • 1
  • 10
  • 16

3 Answers3

22

In Swift 3, Data works as a Collection of UInt8, so you can simply use Array.init.

var received: [UInt8] = []

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
    print("received:\(data))")
    received = Array(data)
}

But, Array.init (or Array.append(contentsOf:)) copies the content of the Data, so it's not efficient when you need to work with huge size of Data.

CodeBender
  • 33,435
  • 12
  • 116
  • 122
OOPer
  • 45,838
  • 6
  • 99
  • 132
0

Got it!

var recived = [UInt8]()

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
        recived.removeAll()
        print("recieved:\(data))")
        recived.append(contentsOf: data)
}
AleyRobotics
  • 960
  • 1
  • 10
  • 16
0

Use withUnsafeBytes:

let data = "ABCD".data(using: .ascii)!
data.withUnsafeBytes {  (pointer: UnsafePointer<UInt8>) in
    //Prints 67 which is the ASCII value of 'C'
    print(pointer[2])
}
Josh Homann
  • 15,266
  • 3
  • 28
  • 33