遍历字节数组以解析出各个长度 [英] Iterate over byte array to parse out individual lengths
问题描述
我正在通过Core Bluetooth(BLE)从硬件设备读取数据。我正在阅读的一种特性是压缩到单个值的结构。
I am reading data off of a hardware device through Core Bluetooth (BLE). One of the charecteristics I am reading is a struct compressed down to a single value. The struct as programmed to the board looks like this:
typedef struct
{
uint8 id;
uint32 dur;
uint16 dis;
} record;
我要解析的大多数其他特征都是单一类型, uint8
, uint32
,依此类推。
Most of the other characteristics I am parsing are of a single type, uint8
, uint32
, so on.
如何循环遍历字节并进行解析每个单独的特征都是本机类型还是 NSString
?有没有一种方法可以遍历 NSData
对象的字节或子字符串?
How can I loop through the bytes and parse each individual characteristic either to native type or an NSString
? Is there a way to iterate over the bytes or substring the NSData
object?
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
}
推荐答案
您可以执行类似的操作以从数据创建结构实例。
You can do something like this to create an instance of your struct from the data.
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
这篇关于遍历字节数组以解析出各个长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!