我有一个NSData对象,其中包含我需要的一些数据。我想要做的是找出数据“FF D8”(JPEG数据的开始)
的位置我怎样才能实现这样的工作?
答案 0 :(得分:9)
首先获取范围,然后获取数据:
// The magic start data object is only created once safely and
// then reused each time
static NSData* magicStartData = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
static const uint8_t magic[] = { 0xff, 0xd8 };
magicStartData = [NSData dataWithBytesNoCopy:(void*)magic length:2 freeWhenDone:NO];
});
// assume data is the NSData with embedded data
NSRange range = [data rangeOfData:magicStartData options:0 range:NSMakeRange(0, [data length])];
if (range.location != NSNotFound) {
// This assumes the subdata doesn't have a specific range and is just everything
// after the magic, otherwise adjust
NSData* subdata = [data subdataWithRange:NSMakeRange(range.location, [data length] - range.location)];
}
答案 1 :(得分:1)
尝试NSData rangeOfData:options:range:
:
NSData *data = /* Your data here */;
UInt8 bytes_to_find[] = { 0xFF, 0xD8 };
NSData *dataToFind = [NSData dataWithBytes:bytes_to_find
length:sizeof(bytes_to_find)];
NSRange range = [data rangeOfData:dataToFind
options:kNilOptions
range:NSMakeRange(0u, [data length])];
if (range.location == NSNotFound) {
NSLog(@"Bytes not found");
}
else {
NSLog(@"Bytes found at position %lu", (unsigned long)range.location);
}