訣竅是轉換616263爲abc。由於您從字符代碼的ASCII表示開始,因此您需要將NSString轉換爲字節數組(或將原始數據源轉換爲數組,而不是首先將其保存爲NSString)。
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
非常感謝你,它的工作:) – 2012-03-11 11:49:34
不客氣! – lnafziger 2012-03-11 14:24:09