代码之家  ›  专栏  ›  技术社区  ›  ilrugel

在字节数组上迭代以解析出各个长度

  •  0
  • ilrugel  · 技术社区  · 10 年前

    我正在通过核心蓝牙(BLE)从硬件设备读取数据。我正在阅读的一个特点是一个压缩为单个值的结构。编程到板上的结构如下所示:

    typedef struct
    {
      uint8          id;
      uint32        dur;
      uint16        dis;
    } record;
    

    我正在解析的大多数其他特征都是单一类型的, uint8 , uint32 等等。

    如何循环遍历字节并将每个单独的特征解析为本机类型或 NSString ? 是否有方法迭代 NSData 对象

    NSData *data = [characteristic value]; // characteristic is of type CBCharacteristic
        NSUInteger len = data.length;
        Byte *bytes = (Byte *)[data bytes];
        for (Byte in bytes) { // no fast enumeration here, but the general intention is to iterate byte by byte
            // TODO: parse out uint8
            // TODO: parse out uint32
            // TODO: parse out uint16
        }
    
    2 回复  |  直到 10 年前
        1
  •  1
  •   Ian MacDonald    10 年前

    您可以执行类似的操作,从数据中创建结构的实例。

    typedef struct
    {
      uint8          id;
      uint32        dur;
      uint16        dis;
    } record;
    
    @implementation YourClass (DataRetrieval)
    - (void)process:(CBCharacteristic *)characteristic {
      record r;
      [[characteristic value] getBytes:&r length:sizeof(r)];
      // r.id
      // r.dur
      // r.dis
    }
    @end
    
        2
  •  0
  •   Community Mohan Dere    8 年前

    而不是在数据中迭代,如果您想提取单个值,则使用Characteristic NSData的subDataWithRange。

    类似于。。。

        //create test data as an example.
        unsigned char bytes[STRUCT_SIZE] = {0x01, 0x00, 0x0, 0x00, 0x02, 0x00, 0x03};
        NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
    
        //assume that you have a packed structure and endianess is correct
        //[0] = id
        //[1] = dur
        //[2] = dur
        //[3] = dur
        //[4] = dur
        //[5] = dis
        //[6] = dis
    
        assert(STRUCT_SIZE == [data length]);
    
        uint8_t     idu = *( uint8_t*)[[data subdataWithRange:NSMakeRange(0, 1)] bytes];
        uint32_t    dur = *(uint32_t*)[[data subdataWithRange:NSMakeRange(1, 4)] bytes];
        uint16_t    dis = *(uint16_t*)[[data subdataWithRange:NSMakeRange(5, 2)] bytes];
    
        assert(1 == idu);
        assert(2 == dur);
        assert(3 == dis);
    

    approach is here

    以及 endianness is here

    我也不确定你是不是 doing any Structure Packing