从iOS上的二进制NSData中减去字符串

时间:2012-01-15 23:35:16

标签: objective-c ios ios4 nsstring nsdata

我有一个字节的NSData,我要从中减去一个字符串。 NSData对象看起来像这样

01 00 00 04 40 00 00 00 00 41 41 41 41 48 47 5A 30 65 58 42 4E 4E 45 45 67 41 
41 41 41 41 45 30 30 51 53 42 74 63 44 51 79 61 58 4E 76 62 51 41 41 41 2B 39 
74 62 32 39 32 41 41 41 41 62 47 31 32 61 47 51 41 41 41 41 41 71 67 59 35 79 
36 6F 47 4F 63 73 41 41 4B 78 45 41 41 43 34 41 41 41 42 41 41 41 42 41 41 41 
41 41 41 41 41 41 41 41 41 41 41 41 41 41 51 41 41 41 41 41 41 41 41 41 41 41

我想提取从第一次出现的“40 00 00 00”到第一次出现的“34”的所有内容

我该怎么做?

由于

果渣

1 个答案:

答案 0 :(得分:3)

不确定您需要哪个字节,这里提取的数据介于“40 00 00 00”到第一次出现的“34”之间,并删除了该范围的数据:

const NSUInteger dataLength = 130;
unsigned char dataBytes[dataLength] = {
0x01,0x00,0x00,0x04,0x40,0x00,0x00,0x00,0x00,0x41,0x41,0x41,0x41,0x48,0x47,0x5A,
0x30,0x65,0x58,0x42,0x4E,0x4E,0x45,0x45,0x67,0x41,0x41,0x41,0x41,0x41,0x45,0x30,
0x30,0x51,0x53,0x42,0x74,0x63,0x44,0x51,0x79,0x61,0x58,0x4E,0x76,0x62,0x51,0x41,
0x41,0x41,0x2B,0x39,0x74,0x62,0x32,0x39,0x32,0x41,0x41,0x41,0x41,0x62,0x47,0x31,
0x32,0x61,0x47,0x51,0x41,0x41,0x41,0x41,0x41,0x71,0x67,0x59,0x35,0x79,0x36,0x6F,
0x47,0x4F,0x63,0x73,0x41,0x41,0x4B,0x78,0x45,0x41,0x41,0x43,0x34,0x41,0x41,0x41,
0x42,0x41,0x41,0x41,0x42,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
0x41,0x41,0x41,0x41,0x41,0x41,0x51,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
0x41,0x41};
NSData *data = [NSData dataWithBytes:dataBytes length:130];

const NSUInteger startBytesLength = 4;
unsigned char startBytes[startBytesLength] = {0x40, 0x00, 0x00, 0x00};
const NSUInteger stopBytesLength = 1;
unsigned char stopBytes[stopBytesLength] = {0x34};


NSData *startData = [NSData dataWithBytes:startBytes length:startBytesLength];
NSData *stopData  = [NSData dataWithBytes:stopBytes  length:stopBytesLength];
NSRange startRange = [data rangeOfData:startData options:0 range:NSMakeRange(0, dataLength)];
NSUInteger start = startRange.location;

NSRange stopRange  = [data rangeOfData:stopData  options:0 range:NSMakeRange(start+startBytesLength, dataLength-(start+startBytesLength))];
NSUInteger length = stopRange.location - start;
NSUInteger stopLocation = stopRange.location+stopBytesLength;

NSData *extractData = [data subdataWithRange:NSMakeRange(start, length)];
NSLog(@"extractData: %@", extractData);

NSMutableData *newData = [NSMutableData data];
[newData appendData:[data subdataWithRange:NSMakeRange(0, start)]];
[newData appendData:[data subdataWithRange:NSMakeRange(stopLocation, dataLength-stopLocation)]];
NSLog(@"newData: %@", newData);

NSLog输出:

  

extractData:< 00414141 4148475a 30655842 4e4e4545 67414141 41414530   30515342 74634451 7961584e 76625141 41412b39 74623239 32414141   41624731 32614751 41414141 41716759 3579366f 474f6373 41414b78   45414143>

     

newData:< 01000004 41414142 41414142 41414141 41414141 41414141   41414141 41514141 41414141 41414141 41>