Binary representation of NSString - nsstring

I need to someone to send me binary data via NSStream and I will convert it into NSString on my end. What's the binary representation that they need to know (byte size, byte order) in order for me to convert the data successfully back into the same string in NSString?

First get the data and convert it into NSData
Then convert NSData to NSString
NSString* newStr = [[[NSString alloc] initWithData:theData
encoding:NSUTF8StringEncoding] autorelease];
If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
(If you have ARC enabled, remove the -autorelease call.)

Related

Having trouble in converting data into NSString from NSData

I want to convert NSData into NSString, my code is below.
NSData *data1 = [object valueForKey:#"college_list"];
NSString *myString =[ NSString stringWithCString:[data1 bytes] encoding:NSUTF8StringEncoding];
What is wrong with this code?
If 'data1' do have some thing in it. Try this:
[[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding]
May be there is some this wrong with your 'object'. Check its data is valid or issue is in its data.

How to assign NSString directly to NSMutableData?

I am developing an application including sqlite database. I want to encrypt and decrypt data's inside the database using AES encryption. I have successfully implemented the AES encryption and inserted the encrypted data's in the database. And am fetching the data's into a NSString.
Then how can I assign that string without changing the string value into a NSMutableData. Because I want to pass that data to AES decrypt method.
Here is some example of NSString <-> NSData conversion:
NSString *someString = #"string";
//NSString to NSData
NSData* data=[someString dataUsingEncoding: [NSString defaultCStringEncoding]];
//NSData to NSString
someString = [[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]];
NSLog(#"%#", someString);
NSString *someString= #"This string will be converted to mutableData in the next line";
NSMutableData *someData = [[someString dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];

Receiving Corrupted Info From Server

On Iphone as well as android I am getting response codes of 200 meaning that I am getting a valid and good response with no errors, but the json that I am receiving has additional characters. I print out the NSData that I receive and it is 580 in length and the NSString, at least when it fails, will have a larger length and print n+ extra characters on the end of the json. I am not sure why this would be but thought I would see if anyone can see what I would be doing incorrectly.
NSString *post = [NSString stringWithFormat:#"referer=%#&username=%#&password=%#", referer, username, password];
NSData *pData = [post dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion:YES];
NSString *pLength = [NSString stringWithFormat:#"%d", [pData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:self.url];
[request setHTTPMethod:#"POST"];
[request setValue:pLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:pData];
[request setTimeoutInterval:30];
NSHTTPURLResponse *response = nil;
NSError *err = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *sData = [NSString stringWithUTF8String:[data bytes]];
I do not receive any errors and every response code that I receive is 200. I have printed out all of these values as well. data length is 580 and sData will vary at times but when it does pass it will be 580 in length, but this can change for different cases. The data will not always be 580 for other users that use the system.
ANSWER:
I solved the problem instead of using
NSString *sData = [NSString stringWithUTF8String:[data bytes]];
You should use
NSString *sData = [[NSString alloc] initWithData: data encoding: NSUTF8String];
This will alloc the correct amount of space based on the NSData object and thus the NSString will never try to access or store more space in that may be behind the last address that should have been accessed.
ANSWER:
I solved the problem instead of using
NSString *sData = [NSString stringWithUTF8String:[data bytes]];
You should use
NSString *sData = [[NSString alloc] initWithData: data encoding: NSUTF8String];
This will alloc the correct amount of space based on the NSData object and thus the NSString will never try to access or store more space in that may be behind the last address that should have been accessed.

NSString stringWithUTF8String return null on device, but ok on simulator

I have a really weird problem. Basically just convert a char to nsstring and store them in an nsmutable array.
But the code runs ok on simulator, but crash on device.
Here is the crash code,
char t = 'A' + i;
NSString* alphabetString = [NSString stringWithUTF8String:&t]; //substringToIndex:1];
[tempArray addObject:alphabetString];
Basically the stringWithUTF8String will return NULL on device, but return valid value on simulator.
The device is an iPhone 4s.
I did not see any notification of changes on NSString stringwithutf8string on iOS5 release.
Thanks.
The address of a single char is not a C-style string. You need to ensure it's null terminated with something like:
char t = 'A' + i;
char s[2]; s[0] = t; s[1] = '\0';
NSString* alphabetString = [NSString stringWithUTF8String:s];
From the docpage:
Parameters
bytes : A NULL-terminated C array of bytes in UTF8 encoding.
You can't pass the address of a single char value to -stringWithUTF8String. That function is expecting a null-terminated string, and you're not passing it one. This results in undefined behavior: anything at all could happen. It might appear to succeed, it might fail benignly, or it might erase your file system. But more likely, it will just crash your program.
You should create a two-character array that's null-terminated instead:
char t[2] = {'A' + i, 0}; // Two-character null-terminated array
NSString* alphabetString = [NSString stringWithUTF8String:t];
Alternatively, you can also use -stringWithFormat: with the %c format specifier to get a string containing a single character:
NSString* alphabetString = [NSString stringWithFormat:#"%c", 'A' + i];

How to convert a XZ compression output to a NSString?

I've successfully set up a small XZ compressor which returns a std::string that contains the compressed output. To process the result I need to "convert" the std::string to a NSString. Unfortunately there are (encoding?) problems:
Even though "abc" is not a good example it shows the difficulty pretty good:
NSString *text = [_text string]; // Length is 3
std::string content = xz_compress([text UTF8String]); // Length is 60
NSString *convertedContent = [NSString stringWithCString:content.c_str() encoding:NSUTF8StringEncoding];
// convertedContent is (null) and 0 characters long
Using NSUnicodeStringEncoding makes the NSString at least 2 characters long but they don't match the ones from std::string.
My questions:
Is this way possible / the preferable way (already unsure about that)?
If so: What encoding do I need to use?
Thanks in advance!
Paul
I assume that xz_compress output is binary data. So, why don't you try and use NSData dataWithBytes:length: method? Possibly you could also try with string::data() instead of string::c_str for the same reason:
NSData* convertedContent = [NSData dataWithBytes:content.data() length:content.length()];

Resources