Conversión de NSString, expresión de tipo de datos, en NSData real

NSString *string1 = @"<616263>";

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

para que cuando yo

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

NSLog(@"%@", string2);

Result: abc

would come out


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

preguntado el 10 de marzo de 12 a las 01:03

1 Respuestas

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

respondido 11 mar '12, 03:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.