如何将数据转换为UInt8数组?
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
print("recieved:\(data)")
let arr: [UInt8] = Data(???)???
}
日志 收到:70字节
答案 0 :(得分:14)
在Swift 3中,Data
作为Collection
的{{1}},因此您只需使用UInt8
。
Array.init
但是,var received: [UInt8] = []
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
print("received:\(data))")
received = Array(data)
}
(或Array.init
)会复制Array.append(contentsOf:)
的内容,因此当您需要处理大量Data
时效率不高。
答案 1 :(得分:0)
知道了!
var recived = [UInt8]()
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
recived.removeAll()
print("recieved:\(data))")
recived.append(contentsOf: data)
}
答案 2 :(得分:0)
let data = "ABCD".data(using: .ascii)!
data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
//Prints 67 which is the ASCII value of 'C'
print(pointer[2])
}