xcode 十进制到十六进制 - Cocoa/Objective-C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10517560/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:14:53  来源:igfitidea点击:

Decimal to Hex - Cocoa/Objective-C

objective-cxcodemacoscocoa

提问by Cindy Broutin

I need to convert some strings which have decimal content. I want these contents in a string, in hex format...

我需要转换一些具有十进制内容的字符串。我想要这些内容在一个字符串中,以十六进制格式......

How can I do it?

我该怎么做?

I tried to use NSScanner but this method seems to be a little bit huge to just make a dec-hex calculation?

我尝试使用 NSScanner 但这种方法似乎有点庞大,只能进行十进制计算?

Thanks for your answers!

感谢您的回答!

回答by Joe

If you know your string only contains a valid decimal number then the simplest way would be:

如果你知道你的字符串只包含一个有效的十进制数,那么最简单的方法是:

NSString *dec = @"254";
NSString *hex = [NSString stringWithFormat:@"0x%lX", 
                  (unsigned long)[dec integerValue]];
NSLog(@"%@", hex);