3

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];
YosiFZ
  • 7,792
  • 21
  • 114
  • 221
  • this isn't quite the same thing, but may be of use: http://stackoverflow.com/questions/1305225/best-way-to-serialize-a-nsdata-into-an-hexadeximal-string – Mike K Jan 01 '12 at 09:14
  • 2
    Try using NSASCIIStringEncoding, some times UTF8 is not ale to convert all the data. – rishi Jan 01 '12 at 09:46
  • The `[NSString alloc] initWithBytes:...` should work. Check your `NSData` object to make sure it contains what you expect. – sjs Jan 01 '12 at 09:50

2 Answers2

8

You can use,

NSString* newStr = [[NSString alloc] initWithData:theData
                                         encoding:NSUTF8StringEncoding];

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

http://homepage.mac.com/mnishikata/objective-c_memo/convert_nsdata_to_nsstring_.html

Community
  • 1
  • 1
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
3

If you're looking to trace the actual hex values of the NSData object, I use this approach:

uint8_t *bytes = (uint8_t*)myNSDataObject.bytes;
NSMutableString *bytesStr= [NSMutableString stringWithCapacity:sizeof(bytes)*2];
for(int i=0;i<sizeof(bytes);i++){
    NSString *resultString =[NSString stringWithFormat:@"%02lx",(unsigned long)bytes[i]];
    [bytesStr appendString:resultString];
}
Dave Cole
  • 2,446
  • 2
  • 20
  • 26