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

发布于 2024-11-06 22:36:03 字数 493 浏览 0 评论 0原文

我有一个无符号字符数组,我想将其转换为十六进制 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]
]];

是否有更好的方法内置函数来实现这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2024-11-13 22:36:03

这个怎么样?

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

我认为这已经是最好的了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文