views:

644

answers:

3

Hello all, this is my first post. 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.

Any help is much appreciated.

A: 

Define an NSCharacterSet that contains the offending characters then filter your string using -stringByTrimmingCharactersInSet:.

Joshua Nozzi
Thanks Joshua. My real issue is the hashedData being NSData, not NSString, so I doubt your answer is workable.
topace
Sorry about that, I had assumed from your original post that you already had a string.
Joshua Nozzi
+2  A: 

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];
Noah Witherspoon
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#jumpTo_67
jsumners
Hi Noah, thanks for your answer. I have actually tried that but it doesn't work. When I print from NSLog, it is showing a string of non-ascii characters like 'uקv' I simply need the angle brackets and spaces removed as mentioned in my original question.
topace
+1  A: 

I have found the solution and I think I was being stupid.

Basically all I had to do is:

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

Once again thank you to all who tried to help. Much appreciated.

topace