开发者

Unsigned Char Array to Hex Representation NSString

开发者 https://www.devze.com 2023-03-05 15:18 出处:网络
I have an unsigned char array and I want to convert it to hex NSString, currently I do it in the following way:

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号