I got the string representation of an NSData
via NSLog
and I would like to construct the original NSData
again for testing purposes, what's the best way to go about doing this?
e.g.
<fe010200 00000000 00011012>
I got the string representation of an NSData
via NSLog
and I would like to construct the original NSData
again for testing purposes, what's the best way to go about doing this?
e.g.
<fe010200 00000000 00011012>
I guess something like:
NSArray *wordStrings =
[string componentsSeparatedByCharactersInSet:
[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
NSMutableData *collectedData = [NSMutableData dataWithCapacity:wordStrings.count * sizeof(unsigned)];
for(NSString *word in wordStrings)
{
NSScanner *scanner = [NSScanner scannerWithString:word];
unsigned newInt;
[scanner scanHexInt:&newInt];
[collectedData appendBytes:&newInt length:sizeof(unsigned)];
}
It creates a scanner for every word after using NSString to enforce spacing whereas it'd be more efficient to do everything in the scanner but it's just for debugging, right? This way you get the wordStrings midpoint to make sure your assumptions about breaking up the string are accurate.
Here is a couple of lines that does a simple scan for numbers and append their values to a NSMutableData object
NSString *dataIn = @"<fe010200 00000000 00011012>";
const char *ptr = [dataIn cStringUsingEncoding:NSUTF8StringEncoding];
NSMutableData *data = [NSMutableData data];
while (*ptr) {
unsigned char c1 = *ptr;
ptr++;
if (isalpha(c1))
c1 = (10 + c1 - 'a')<<4;
else if (isnumber(c1))
c1 = (c1 - '0')<<4;
else
continue;
if (!*ptr)
break; // Shouldn't occure -- bad input
unsigned char c2 = *ptr;
ptr++;
if (isalpha(c2))
c2 = 10 + c2 - 'a';
else if (isnumber(c2))
c2 = c2 - '0';
c1 = c1 | c2;
[data appendBytes:&c1 length:1];
}
NSLog(@"%@", data);