ios - 数据值溢出

标签 ios swift bluetooth bluetooth-lowenergy

我对数据对象如何快速工作感到有点困惑。我正在尝试使用蓝牙写入值,我需要写入的值之一是 500。为了写入,您需要在发送之前将值转换为数据对象。这是我正在使用的代码。

if(characteristic != nil){
   var byteCount = 1
   if(sensitivity > 255){
      byteCount = 2
   }
   let data = Data.init(bytes: &sensitivity, count: byteCount)
   peripheral.writeValue(data, for: sensCharacteristic!, type: CBCharacteristicWriteType.withResponse)
   peripheral.readValue(for: sensCharacteristic!)
}else{
   print("No bluetooth Connection")
}

根据我的理解,如果我尝试发送一个需要超过一个字节的值,那么它将溢出,因此当我发送 500 时,它写入的值实际上是 244。因此我尝试写入并发送 2 个字节但是我得到的值是 244101。我不确定这个值是从哪里来的。隐藏500的正确方法是什么?

每当读取一个特征并将其放入标签中时,就会调用此函数。它所做的只是遍历数据并将每个字节添加到一个字符串中。

func readCharacteristic(data: Data) -> String {
    var characterString = ""
    for byte in data {
        let c = String(byte)
        characterString.append(c)
    }
    return characterString
}

最佳答案

基于这篇 SO 帖子:round trip Swift number types to/from Data(Wei Jay 指出)...

试试这个:

func readCharacteristic(data: Data) -> Int {
    return data.withUnsafeBytes { $0.pointee }
}

注意:该帖子提供了将数据转换为不同数据类型的各种方法 - Int、Float、Double 等 - 因此如果您知道您只会读取 Int,则可以使用此值(value)。否则,只需在此 + 另一篇文章的基础上构建。

关于ios - 数据值溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44725104/

相关文章:

ios - 如何在我的 UICollectionView 上重新加载数据?

Iphone App Release with possible Patent or License issues

swift - 如何按一个轴按比例缩放 Sprite - swift/spritekit

android - BluetoothGatt 显示 10,000 个相同的服务特征

iphone - NSString 到 NSNumber 的格式

swift - 带有圆角矩形的 NSBezierPath 没有光滑的角

swift - 如何在类层次结构中正确实现 Equatable 协议(protocol)?

android - 销毁 Activity 时在订阅外注销 BroadcastReceiver

android - 我的应用程序出现蓝牙问题

ios - 如何从 currentDirectoryPath 获取 NSURL