NSData to display as a string

I am building an iPhone app and stick to the following:

unsigned char hashedChars[32]; CC_SHA256([inputString UTF8String], [inputString lengthOfBytesUsingEncoding:NSASCIIStringEncoding], hashedChars); NSData *hashedData = [NSData dataWithBytes:hashedChars length:32]; NSLog(@"hashedData = %@", hashedData); 

The magazine shows how:

 hashedData = <abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh abcdefgh> 
  • note hashedData is NSData, not NSString

But I need to convert hashedData to NSString, which looks like this:

 NSString *someString = @"abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh"; 

So basically the result should be similar to hashedData, except that I don't need angle brackets and the spaces between them.

+43
iphone nsstring nsdata
Apr 16 '10 at 13:38
source share
3 answers

I found a solution, and I think I was stupid.

Basically all I needed to do:

NSString *someString = [NSString stringWithFormat:@"%@", hashedData]; // force NSData to become NSString

Thanks again to everyone who tried to help, very much appreciated.

+22
Apr 16 '10 at 17:41
source share

Use the NSString initWithData: encoding: method.

 NSString *someString = [[NSString alloc] initWithData:hashedData encoding:NSASCIIStringEncoding]; 

(edit the response to your comment :)

In this case, Joshua's answer helps:

 NSCharacterSet *charsToRemove = [NSCharacterSet characterSetWithCharactersInString:@"< >"]; NSString *someString = [[hashedData description] stringByTrimmingCharactersInSet:charsToRemove]; 
+63
Apr 16 2018-10-16T00:
source share

Define an NSCharacterSet that contains offensive characters, then filter your string with -stringByTrimmingCharactersInSet :.

+2
Apr 16 2018-10-16T00:
source share



All Articles