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

时间:2015-02-27 20:15:32

标签: ios core-bluetooth

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

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

我正在解析的大多数其他特征都是单一类型,uint8uint32,依此类推。

如何遍历字节并将每个特征解析为本机类型或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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

不是迭代数据,而是想要提取单个值,而是使用特征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

相关问题