How can I return back to an NSString from the byte date of the NSString containing this character: fl ?
NSString *inflatedString01 = @"fl";
// original code that was the problem!
NSData *dataOfString = [NSData dataWithBytes:[inflatedString01 UTF8String] length:[inflatedString length]];
// code that fixes the problem
//NSData *dataOfString = [inflatedString01 dataUsingEncoding:NSUTF8StringEncoding]; //thanks zneak
NSLog(@"%@",inflatedString01);
NSLog(@"%i",[inflatedString01 length]);
NSLog(@"%@",dataOfString);
NSLog(@"%i",[dataOfString length]);
NSString *stringFromData = [NSString stringWithCString:[dataOfString bytes] encoding:NSUTF8StringEncoding]
NSLog(@"%@",stringFromData);
The output of the above gives:
2012-01-02 08:47:48.963 TestApp[74363:fe03] fl
2012-01-02 08:47:49.262 TestApp[74363:fe03] 1
2012-01-02 08:47:49.540 TestApp[74363:fe03] <ef>
2012-01-02 08:47:49.924 TestApp[74363:fe03] 1
2012-01-02 08:47:50.787 TestApp[74363:fe03] (null)
I’d like to see fl instead of (null) for the last NSLog output. I’m guessing there is a significance with the ‘ef’ output of NSData.
The problem is the discrepancy of the character size versus the binary size. When you call
[NSString length], what you get is the number of logical characters in the string, not the number of bytes required to store it in an arbitrary encoding. The character fl is one logical character for theNSStringclass, but its UTF-8 encoding isef ac 82: it takes up 3 bytes.Your call to
[NSData dataWithBytes:length:]receives a pointer to these 3 bytes, but then[inflatedString01 length]tells that it’s only one character and you pass that as the number of bytes; this is why your data contains onlyef.strlen, not being encoding-aware, will just count the number of bytes in a C string until it finds a zero, so it will accurately return the number of bytes in an UTF-8 string (as you noted in your comment).The best solution would probably to simply call
[inflatedString01 dataUsingEncoding:NSUTF8StringEncoding]to get the bytes.