迭代字节数组,parsing出各个长度
我正在通过核心蓝牙(BLE)读取硬件设备的数据。 我正在读的一个特性是一个压缩到一个值的结构。 程序devise到板上的结构如下所示:
typedef struct { uint8 id; uint32 dur; uint16 dis; } record;
我parsing的大多数其他特征是单一types, uint8
, uint32
,等等。
我如何循环访问字节,并将每个单独的特征parsing为本机types或NSString
? 有没有办法迭代字节或子string的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 }
你可以这样做,从数据创build你的结构的一个实例。
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
而不是迭代您的数据,如果您想要提取个别值,您使用特征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);
这个方法的一个很好的描述就在这里
在这里 ,一个endianness的方法
我也不确定你是否在做任何结构包装