Swift得到十进制的characteristic.value

时间:2016-12-16 20:46:18

标签: ios swift bluetooth bluetooth-lowenergy

我尝试使用Swift 3在Xcode中创建一个小型iOS应用程序。我尝试连接到BLE设备,然后读取电池电量。

我收到了这个回复:

  

... UUID =电池电量,属性= 0x12,值=< 30> ...

然后我尝试将HEX 30转换为十进制48。 但我不知道如何。

我试过这个:

print(String(bytes: characteristic.value!, encoding: String.Encoding.utf8))
print(Int(strtoul(str, nil, 16)))
let dataBLE = String(data: characteristic.value!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
print(dataBLE)

但这些都不起作用。如何使用characteristic.value的值从十六进制转换为十进制?

2 个答案:

答案 0 :(得分:2)

org.bluetooth.characteristic.battery_level(0x2A19)的值似乎是单个uint8(Swift中的UInt8)。 characteristic.value!的结果是Data,它是UInt8的集合,在您的情况下,它只包含一个UInt8值。

试试这个:

print(characteristic.value![0])

但是,当您需要在应用中使用其他各种特性时(对于使用BLE的应用而言,这是非常常见的情况),leanne评论中显示的链接文章将非常有用。

答案 1 :(得分:1)

这应该有效:

let data = characteristic.value
var byte:UInt8 = 0
data.copyBytes(to: &byte, count: 1)

let valueInInt = Int(byte)
print(valueInInt)