ios 如何在 Objective-C 中将 HEX 转换为 NSString?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6421282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert HEX to NSString in Objective-C?
提问by user403015
I have a NSString with hex string like "68656C6C6F" which means "hello".
我有一个带有十六进制字符串的 NSString,例如“68656C6C6F”,意思是“你好”。
Now I want to convert the hex string into another NSString object which shows "hello". How to do that ?
现在我想将十六进制字符串转换为另一个显示“hello”的 NSString 对象。怎么做 ?
回答by RedBlueThing
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;
}
回答by Morten Fast
This should do it:
这应该这样做:
- (NSString *)stringFromHexString:(NSString *)hexString {
// The hex codes should all be two characters.
if (([hexString length] % 2) != 0)
return nil;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [hexString length]; i += 2) {
NSString *hex = [hexString substringWithRange:NSMakeRange(i, 2)];
NSInteger decimalValue = 0;
sscanf([hex UTF8String], "%x", &decimalValue);
[string appendFormat:@"%c", decimalValue];
}
return string;
}
回答by dancl
I think the people advising initWithFormat is the best answer as it's objective-C rather than a mix of ObjC, C.. (although the sample code is a bit terse).. I did the following
我认为建议 initWithFormat 的人是最好的答案,因为它是目标 C 而不是 ObjC、C 的混合......(虽然示例代码有点简洁).. 我做了以下
unsigned int resInit = 0x1013;
if (0 != resInit)
{
NSString *s = [[NSString alloc] initWithFormat:@"Error code 0x%lX", resInit];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Initialised failed"
message:s
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[s release];
}
回答by Aditya
+(NSString*)intToHexString:(NSInteger)value
{
return [[NSString alloc] initWithFormat:@"%lX", value];
}