Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 634
YosiFZ Avatar asked Sep 08 '25 14:09

YosiFZ


2 Answers

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

like image 53
Midhun MP Avatar answered Sep 10 '25 04:09

Midhun MP


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];
}
like image 22
Dave Cole Avatar answered Sep 10 '25 04:09

Dave Cole