Click here to Skip to main content
13,900,557 members
Rate this:
Please Sign up or sign in to vote.
Hi All,
I know this is suppose to be very straight forward and simple but i have been trying to convert NSData to NSString using Obj-C but the outputs are not what I really wanted.

my NSData variable:
NSData *blockData = [NSData dataWithBytes:&data length:sizeof(data)];

I'm trying to print it in NSLog like below:
NSLog(@"sneding block: %@", blockData);

the output is like:
018-06-13 08:05:18.641965-0400 sendData[3016:1171273] sneding: <0000e992 ffff0300 00884242 4242ffff ffff>

I need the output to be in string or numbers not hex, i have done it in java by converting byte[] array to string: Arrays.toString(byte[]) the output something like: [-24,14,60,103,-119,14,-118,12,-117,13,18,84,81,-118,10,-117,11,-22]

any ideas?
Thanks in advance

What I have tried:

I tried to use NSUTF8StringEncoding
NSString *str = [[NSString alloc] initWithData:blockData encoding:NSUTF8StringEncoding];//returns null

also tried NSASCIIStringEncoding with no luck
[[NSString alloc] initWithData:blockData encoding:NSASCIIStringEncoding];//returns ascii codes
Updated 13-Jun-18 5:37am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You can do it like this:

NSMutableString * str = [NSMutableString string];
for (int i = 0; i<sizeof(data); i++)
    [str appendFormat:@"%d ", data[i]];

Samira Radwan 13-Jun-18 13:36pm
Thank you!
this solution works very well when using array of bytes or signed char. but if `data` is of type `NSData` I got error: expected method to read array element not found on object of type NSData. we can't just read data[i] if it's NSData
User 7429338 13-Jun-18 13:48pm
If you have an object blockData of type NSData, you can convert it into a byte array data like so:
data = [blockData bytes];

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190306.1 | Last Updated 13 Jun 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100