MTA MTA - 1 year ago 124
Objective-C Question

NSData bytes to string

I get NSData of bytes that look like this:

2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d2d2d2d 2d353731 35343039 37373139
34383437 34303832 30333533 30383232 380d0a43 6f6e7465 6e742d44 6973706f 73697469 6f6e3a20
666f726d 2d646174 613b206e 616d653d 2266696c 65223b20 66696c65 6e616d65
3d224265 61636820 426f7973 202d2047 6f6f6420 56696272 6174696f 6e732e6d

and i want to convert it to NSString, i tried this method but it give me a nil to the string:

NSString* postInfo = [[NSString alloc] initWithBytes:[postDataChunk bytes] length:[postDataChunk length] encoding:NSUTF8StringEncoding];

Answer Source

You can use,

NSString* newStr = [[NSString alloc] initWithData:theData

If the data is null-terminated, you should instead use

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

for further reference see these links:

Convert UTF-8 encoded NSData to NSString

NSString class reference

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download