6

如何将数据转换为 UInt8 数组?

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

收到的日志:70 字节

4

3 回答 3

21

在 Swift 3 中,Data作为 a Collectionof工作UInt8,所以你可以简单地使用Array.init.

var received: [UInt8] = []

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

但是,(Array.initArray.append(contentsOf:))复制.DataData

于 2016-11-11T14:32:32.923 回答
0

知道了!

var recived = [UInt8]()

func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
        recived.removeAll()
        print("recieved:\(data))")
        recived.append(contentsOf: data)
}
于 2016-11-10T19:56:26.880 回答
0

使用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])
}
于 2016-11-10T19:56:29.713 回答