NSData to display as a string

topace picture topace · Apr 16, 2010 · Viewed 41.8k times · Source

I am building an iPhone app and stuck with 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 log is showing like:

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

But what I need is to convert hashedData into NSString that looks like:

NSString *someString = @"abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh";

So basically the result needs to be like hashedData except I don't want the angle brackets and spaces in between.

Answer

Noah Witherspoon picture Noah Witherspoon · Apr 16, 2010

Use the NSString initWithData:encoding: method.

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

(edit to respond to your comment:)

In that case, Joshua's answer does help:

NSCharacterSet *charsToRemove = [NSCharacterSet characterSetWithCharactersInString:@"< >"];
NSString *someString = [[hashedData description] stringByTrimmingCharactersInSet:charsToRemove];