如何从Hex String获取NSData?

时间:2017-02-13 07:42:46

标签: ios objective-c nsstring nsdata

我需要通过melodyManager&发送数据免于NonHexCharacters,

我已经完成了链接How to convert an NSData into an NSString Hex string?

NSData from hex String?

在两个链接中,我无法获得NonHexFree字符数据。

我的输入字符串是

0x0009 0xB0 0xFD 0xC2 0xA1 0x06 0x01%@040404 0x01 0xss1 0xhh 0xyy1

我需要将此字符串转换为NSData,该字符不含非字符字符,我的意思是数据应该只有十六进制字符串,例如0-9符号& A,B,C,D,E,F(或者a,b,c,d,e,f)并且还删除具有0x前缀和空格的空间。输出字符串应为0009B0FDC2A10601040404111

然后它应该转换为`NSData'

1 个答案:

答案 0 :(得分:1)

要清理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 = @"0123456789abcdefABCDEF";
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];