Steve Ham
Steve Ham

Reputation: 3154

Converting NSString, data type expression, to actual NSData

NSString *string1 = @"<616263>";

I want to make this into NSData *data1 = <616263>;

so that when I

NSString *string2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];

NSLog(@"%@", string2);

Result: abc

would come out

p.s.

<616263>, this is data expression of @"abc"

Upvotes: 0

Views: 298

Answers (1)

lnafziger
lnafziger

Reputation: 25740

The trick is converting 616263 to abc. Since you are starting with the ASCII representation of the character codes, you need to convert your NSString to an array of bytes (or your original data source to an array instead of saving it as an NSString in the first place).

NSString *string1 = @"616263";

// Make sure that buffer is big enough!
char sourceChars[7];
[string1 getCString:sourceChars maxLength:7 encoding:NSUTF8StringEncoding];

char destBuffer[3];
char charBuffer[3];

// Loop through sourceChars and convert the ASCII character groups to char's
// NOTE:  I assume that these are always two character groupings per your example!
for (int index = 0; index < [string1 length]; index = index + 2) {
    // Copy the next two digits into charBuffer
    strncpy(charBuffer, &sourceChars[index], 2);
    charBuffer[2] = '\0';
    // convert charBuffer (ie 61) from hex to decimal
    destBuffer[index / 2] = strtol(charBuffer, NULL, 16);
}

// destBuffer is properly formatted:  init data1 with it.
NSData *data1 = [NSData dataWithBytes:destBuffer length:[string1 length]/2];

// Test
NSString *string2 = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(@"%@", string2);  // Prints abc

Upvotes: 2

Related Questions