我正通过BLE从传感器检索数据。 我正在将字节从NSData转换为带符号的16位整数数组。但是我收到错误说
Argument type '[Int16]' does not conform to expected type '_Pointer'
有更好的方法吗?任何帮助表示赞赏。
func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
if characteristic.uuid == tempUUID {
let dataBytes = characteristic.value
let dataCount = dataBytes?.count
var dataArray = [Int16](repeating: 0, count: dataCount!)
dataBytes.getBytes(dataArray, length:dataCount! * MemoryLayout<Int16>.size)
let finalAnswer = Double(dataArray[1])/128
答案 0 :(得分:1)
这是你可以将数据复制到整数数组中的方法(Swift 3/4):
if let data = characteristic.value {
let i16value = data.withUnsafeBytes { (ptr: UnsafePointer<Int16>) in
ptr[1]
}
let finalAnswer = Double(i16value)/128
}
如果您只需要一个值,那么您可以在不使用的情况下访问它 创建一个数组:
if let data = characteristic.value {
let i16value = data.subdata(in: 2..<4).withUnsafeBytes {
UnsafeRawPointer($0).load(as: Int16.self)
}
let finalAnswer = Double(i16value)/128
}
另一种选择:
UITextField