gpt4 book ai didi

swift - 将 BLE 当前时间转换为日期

转载 作者:行者123 更新时间:2023-11-28 13:25:30 25 4
gpt4 key购买 nike

我正在尝试从蓝牙设备读取当前时间。

我目前得到一个 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 年,但我不确定如何在代码中转换它。

最佳答案

要从数据/字节转换为数字类型,您可以查看此 post

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"

关于swift - 将 BLE 当前时间转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58419880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com