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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
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 :)
NSString doesn't have method hexStringWithData. You have to use NSData initWithBytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.