遍历字节数组以解析出各个长度

Iterate over byte array to parse out individual lengths

我正在通过核心蓝牙 (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
    }

您可以像这样从数据中创建结构实例。

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

而不是遍历你的数据,如果你想提取单个值,你可以使用 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