3

I have an unsigned char array and I want to convert it to hex NSString, currently I do it in the following way:

unsigned char result[16];
// Fill the array

NSString *myHexString = [NSString stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
    result[0], result[1], result[2], result[3], 
    result[4], result[5], result[6], result[7],
    result[8], result[9], result[10], result[11],
    result[12], result[13], result[14], result[15]
]];

Is there a better way to built-in function that achieves that?

MByD
  • 135,866
  • 28
  • 264
  • 277

1 Answers1

10

How about this?

NSMutableString *hex = [NSMutableString string];
for (int i=0; i<16; i++)
    [hex appendFormat:@"%02x", result[i]];

// And if you insist on having the hex in an immutable string:
NSString *immutableHex = [NSString stringWithString:hex];

You can also turn the code into a category to keep things nice:

@implementation NSString (Hex)

+ (NSString*) hexStringWithData: (unsigned char*) data ofLength: (NSUInteger) len
{
    NSMutableString *tmp = [NSMutableString string];
    for (NSUInteger i=0; i<len; i++)
        [tmp appendFormat:@"%02x", data[i]];
    return [NSString stringWithString:tmp];
}

@end

Then your code boils down to:

unsigned char result[16] = {…};
NSString *hexString = [NSString hexStringWithData:result ofLength:16];

I think that’s about as nice as it gets.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • thanks, but that's not what I mean, especially because I will need to convert it to NSString right after. I want to know if there's a built in function. – MByD May 12 '11 at 12:07
  • `NSMutableString` descends from `NSString`, so that you can use it wherever an `NSString` is needed. If you really want to, you can easily create an immutable string from the mutable one, I have edited the answer to add an example. I don’t think there’s a built-in function to do this. – zoul May 12 '11 at 12:11
  • thanks for the update, I was just wondering if there's a built in function for that. Seems like the answer is no, but you did make it nice enough :) – MByD May 12 '11 at 12:18
  • NSString doesn't have method hexStringWithData. You have to use NSData initWithBytes – kraag22 Oct 21 '14 at 08:43