我正在尝试从蓝牙设备读取当前时间。
我目前有一个10字节的数组,但不确定如何将其转换为可读的数组。
这是我从中读取的代码。
private func printTime(from characteristic: CBCharacteristic) {
guard let timeData = characteristic.value else { return }
let byteArray = [UInt8](timeData)
print("Time ",byteArray, "timeData ", timeData)
}
这是输出。
Time [224, 7, 1, 3, 4, 36, 5, 0, 0, 1] timeData 10 bytes
这是我针对该特性针对该设备获得的规格。
3.2.1. Current Time
3.2.1.1. UUID: 2A2B
3.2.1.2. Read: Yes
3.2.1.3. Write: Yes
3.2.1.4. Notify: Yes
3.2.1.5. Value: byte[10]
3.2.1.6. Description: 0 – 1: Year
2: Month
3: Day
4: Hour
5: Minute
6: Seconds
7: Day of Week
8: 256 Fractions of a Seconds
9: Adjust Reason
所以我知道那是224,7。我假设是2016年,但是我不确定如何在代码中进行转换。
要将数据/字节转换为数字类型,可以查看此文章
extension Numeric {
init<D: DataProtocol>(_ data: D) {
var value: Self = .zero
let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
assert(size == MemoryLayout.size(ofValue: value))
self = value
}
}
extension DataProtocol {
func value<N: Numeric>() -> N { .init(self) }
var uint16: UInt16 { value() }
}
现在,您可以轻松地将字节转换为任何数字类型:
let timeData: [UInt8] = [224, 7, 1, 3, 4, 36, 5, 0, 0, 1]
let timeDate = DateComponents(calendar: .current,
timeZone: .current,
year: Int(timeData[0..<2].uint16),
month: Int(timeData[2]),
day: Int(timeData[3]),
hour: Int(timeData[4]),
minute: Int(timeData[5]),
second: Int(timeData[6])).date!
timeDate // "Jan 3, 2016 at 4:36 AM"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句