Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData to NSString returns Null

Tags:

objective-c

I have searched. But still couldnt get it.

I'm converting NSdata to NSString. When I do [data description]; it returns me <00000000 31323334 35363738> Yes, Im receiving my string @"12345678".

How do I convert it to NSString appropriately? I tried

NSString *b = [NSString stringWithUTF8String:[data bytes]];
NSString *a = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];

Both returns me null. Any idea? Thanks

Hi all, Thanks for all suggestion. It appears to be constant whereby theres a null character infront always. So whenever I receive something, i just remove the first <00000000>, then its working fine already

like image 267
user774150 Avatar asked Apr 16 '12 17:04

user774150


1 Answers

This happens if the encoding is incorrect.

Try using ASCII to test out. ASCII almost certainly work to retrive somekind of string. If it's only numbers it will probably work.

NSString *a = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSASCIIStringEncoding];

Most common except UTF-8 enconding is:

NSASCIIStringEncoding
NSUnicodeStringEncoding
NSISOLatin1StringEncoding
NSISOLatin2StringEncoding
NSSymbolStringEncoding

try them out and see if they work.

like image 191
Nic Avatar answered Sep 22 '22 14:09

Nic