无符号字符数组到十六进制表示NSString

时间:2011-05-12 12:02:28

标签: objective-c nsstring hex arrays

我有一个unsigned char数组,我想把它转换为十六进制NSString,目前我是按照以下方式进行的:

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]
]];

是否有更好的内置函数方法可以实现这一目标?

1 个答案:

答案 0 :(得分:9)

这个怎么样?

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];

您还可以将代码转换为类别以保持良好状态:

@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

然后你的代码归结为:

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

我认为这和它一样好。