如何在Objective-C中将HEX转换为NSString? [英] How to convert HEX to NSString in Objective-C?

查看:224
本文介绍了如何在Objective-C中将HEX转换为NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有十六进制字符串的NSString,如68656C6C6F,意思是你好。

I have a NSString with hex string like "68656C6C6F" which means "hello".

现在我想将十六进制字符串转换为另一个显示hello的NSString对象。怎么做?

Now I want to convert the hex string into another NSString object which shows "hello". How to do that ?

推荐答案

我确信有更好,更聪明的方法来做到这一点,但这个解决方案确实有效。

I am sure there are far better, cleverer ways to do this, but this solution does actually work.

NSString * str = @"68656C6C6F";
NSMutableString * newString = [[[NSMutableString alloc] init] autorelease];
int i = 0;
while (i < [str length])
{
    NSString * hexChar = [str substringWithRange: NSMakeRange(i, 2)];
    int value = 0;
    sscanf([hexChar cStringUsingEncoding:NSASCIIStringEncoding], "%x", &value);
    [newString appendFormat:@"%c", (char)value];
    i+=2;
}

这篇关于如何在Objective-C中将HEX转换为NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆