Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NSString to NSData and vice versa

I am having an issue while trying to convert NSString to NSData and vice versa. I am trying to store encrypted string to my database. For that I am using AES algorithm. Now what I am doing is I get encrypted NSData and I am converting this to NSString using following:

// Not woking
NSString *strTemp = [[NSString alloc] initWithData:encData encoding:NSUTF8StringEncoding]; 

// Working
NSString *strTemp = [[NSString alloc] initWithData:encData encoding:NSASCIIStringEncoding];

Why NSData is not converting while using NSUTF8StringEncoding. Same way when I try to convert the string got by NSASCIIStringEncoding using:

// Not working
[strTemp dataUsingEncoding:NSASCIIStringEncoding];

// Working
[strTemp dataUsingEncoding:NSUTF8StringEncoding];

Why NSASCIIStringEncoding is not working while converting the NSString to NSData?

like image 958
Kapil Choubisa Avatar asked Jul 19 '11 10:07

Kapil Choubisa


2 Answers

NSString to NSData:

NSString* str= @"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

NSData to NSString:

NSString* newStr = [[NSString alloc] initWithData:theData
                                         encoding:NSUTF8StringEncoding];
like image 187
Maulik Avatar answered Oct 27 '22 05:10

Maulik


Please mind that NSASCIIStringEncoding and NSUTF8StringEncoding need to match the characters in the string.

like image 31
zaph Avatar answered Oct 27 '22 04:10

zaph