简体   繁体   中英

How to get NSData From Hex String?

I need to send data over melodyManager & free from NonHexCharacters,

I already gone throught link How to convert an NSData into an NSString Hex string?

NSData from hex String?

In Both links i am not able to get NonHexFree charater data.

My input string is this,

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

I need to convert this string into NSData which is free from nonhex characters i mean data should get only of hex string like from 0-9 symbols & A, B, C, D, E, F (alternatively a, b, c, d, e, f) and also remove space with 0x prefixes & output string should be 0009B0FDC2A10601040404111

then it should get converted to `NSData'

For cleaning nonHex characters check this,

NSString *input = @"0x0009 0xB0 0xFD 0xC2 0xA1 0x06 0x01%@040404 0x01 0xss1 0xhh 0xyy1";

I am considering that you don't required '0x' into your case.

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:@""];

Then resultant hexstring pass to scan hexString & append into NSMUtableData then convert it into 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM