Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Google Sign In with OpenID

NSData to Hex String

PHANTOMIASPHANTOMIAS Posts: 100Registered Users
edited November 2009 in iPhone SDK Development
Hello!

I have a SecKeyRef () from generating a private/public key pair with the CryptoExercise from Apple (CryptoExercise).

This is a NSData which I will transform to a hex string.
I found these two implementations:
@interface NSData (NSData_HexAdditions)
- (NSString*) stringWithHexBytes1;
- (NSString*) stringWithHexBytes2;
@end

@implementation NSData (NSData_HexAdditions)
- (NSString*) stringWithHexBytes {
	NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([self length] * 2)];
	const unsigned char *dataBuffer = [self bytes];
	int i;
	for (i = 0; i < [self length]; ++i) {
		[stringBuffer appendFormat:@"%02X", (unsigned long)dataBuffer[i]];
	}
	return [[stringBuffer copy] autorelease];
}

- (NSString*)stringWithHexBytesss {
	static const char hexdigits[] = "0123456789ABCDEF";
	const size_t numBytes = [self length];
	const unsigned char* bytes = [self bytes];
	char *strbuf = (char *)malloc(numBytes * 2 + 1);
	char *hex = strbuf;
	NSString *hexBytes = nil;

	for (int i = 0; i<numBytes; ++i) {
		const unsigned char c = *bytes++;
		*hex++ = hexdigits[(c >> 4) & 0xF];
		*hex++ = hexdigits[(c ) & 0xF];
	}
	*hex = 0;
	hexBytes = [NSString stringWithUTF8String:strbuf];
	free(strbuf);
	return hexBytes;
}
@end
And I use it so:
[publicKey stringWithHexBytes1]
[publicKey stringWithHexBytes2]

Both results are the same, but which one is faster and should I use?

And: I put the above source code in my ABCController.m. I think it is not a good idea to do that. Should I create a NSData.h and NSData.m class for that code or what's the best solution?

Thanks & Regards.
Sign In or Register to comment.