swift3 中的数据到 Int / String
Data to Int / String in swift3
我正在使用 BLE 设备。设备正在以特定 UUID 发送值。
这是我将数据转换为 Int 或 String 以供显示的代码。
...
else if characteristic.uuid == CBUUID(string: UUID_CHANGEIN_BATTERY_LEVEL) {
// let battery = UInt32(bigEndian: ((characteristic.value?.withUnsafeBytes { [=10=].pointee }) ?? 0))
let array : [UInt8] = [0, 0, 0]
var data = Data(bytes: array)
if characteristic.value != nil {
data.append(characteristic.value!)
}
let battery = UInt32(bigEndian: ((data.withUnsafeBytes { [=10=].pointee }) ?? 0))
print("battery level changed\nNew level is \(getInt(fromData: characteristic.value!, start: 0))!")
// lblBattery.text = (String(data: characteristic.value!, encoding: String.Encoding.utf8) ?? "0") + "%"
lblBattery.text = "\(getInt(fromData: characteristic.value!, start: 0))%"
}
...
func getInt(fromData data: Data, start: Int) -> Int32 {
let intBits = data.withUnsafeBytes({(bytePointer: UnsafePointer<UInt8>) -> Int32 in
bytePointer.advanced(by: start).withMemoryRebound(to: Int32.self, capacity: 4) { pointer in
return pointer.pointee
}
})
return Int32(bigEndian: intBits)
// return Int32(littleEndian: intBits)
}
我已经检查了 BLE 扫描仪 iOS 应用程序,它显示 0x2b01
作为值,它还显示 43 作为电池百分比。
如上所示,我写了 3-4 种代码。
但是 none 他们给了我 43 作为价值。
请帮我找出我做错了什么或者我缺少什么来满足我的要求。
swift 3
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let value = [UInt8](characteristic.value!)
print("Battery ", value[0], "%")
}
我正在使用 BLE 设备。设备正在以特定 UUID 发送值。
这是我将数据转换为 Int 或 String 以供显示的代码。
...
else if characteristic.uuid == CBUUID(string: UUID_CHANGEIN_BATTERY_LEVEL) {
// let battery = UInt32(bigEndian: ((characteristic.value?.withUnsafeBytes { [=10=].pointee }) ?? 0))
let array : [UInt8] = [0, 0, 0]
var data = Data(bytes: array)
if characteristic.value != nil {
data.append(characteristic.value!)
}
let battery = UInt32(bigEndian: ((data.withUnsafeBytes { [=10=].pointee }) ?? 0))
print("battery level changed\nNew level is \(getInt(fromData: characteristic.value!, start: 0))!")
// lblBattery.text = (String(data: characteristic.value!, encoding: String.Encoding.utf8) ?? "0") + "%"
lblBattery.text = "\(getInt(fromData: characteristic.value!, start: 0))%"
}
...
func getInt(fromData data: Data, start: Int) -> Int32 {
let intBits = data.withUnsafeBytes({(bytePointer: UnsafePointer<UInt8>) -> Int32 in
bytePointer.advanced(by: start).withMemoryRebound(to: Int32.self, capacity: 4) { pointer in
return pointer.pointee
}
})
return Int32(bigEndian: intBits)
// return Int32(littleEndian: intBits)
}
我已经检查了 BLE 扫描仪 iOS 应用程序,它显示 0x2b01
作为值,它还显示 43 作为电池百分比。
如上所示,我写了 3-4 种代码。
但是 none 他们给了我 43 作为价值。
请帮我找出我做错了什么或者我缺少什么来满足我的要求。
swift 3
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let value = [UInt8](characteristic.value!)
print("Battery ", value[0], "%")
}