對於清潔nonHex字符進行檢查,
NSString *input = @"0x0009 0xB0 0xFD 0xC2 0xA1 0x06 0x01%@040404 0x01 0xss1 0xhh 0xyy1";
我正在考慮,你不要求加「0x」到你的情況。
NSString * output = [input stringByReplacingOccurrencesOfString:@"0x" withString:@""
options:NSCaseInsensitiveSearch range:NSMakeRange(0, input.length)];
NSString * hexChars = @"abcdefABCDEF";
NSCharacterSet *hexc = [NSCharacterSet characterSetWithCharactersInString:hexChars];
NSCharacterSet *invalidHexc = [hexc invertedSet];
NSString * allHex = [[output componentsSeparatedByCharactersInSet:invalidHexc] componentsJoinedByString:@""];
然後得到的hexstring通過掃描的hexstring &追加到NSMUtableData
然後將其轉換爲NSData的,
//Check condition if required `allHex.lenght != nil`
NSMutableData *result = [[NSMutableData alloc] init];
int i = 0;
for (i = 0; i+2 <= allHex.length; i+=2) {
NSRange range = NSMakeRange(i, 2);
NSString* hexStr = [allHex substringWithRange:range];
NSScanner* scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
unsigned char uc = (unsigned char) intValue;
[result appendBytes:&uc length:1];
}
NSData * data = [NSData dataWithData:result];
這個問題有點過於抽象。什麼是melodyManager,什麼是NonHexFree?你做了什麼?請向我們展示代碼並描述你卡在哪裏。 –
那麼你期望的結果是什麼?它是「000090B00FD0C20A100600104040400101001」 –
http://stackoverflow.com/a/7318062/1091539 – Mutawe