【问题标题】:How can I convert hex number to integers and strings in Objective C?如何在 Objective C 中将十六进制数转换为整数和字符串?
【发布时间】:2010-10-30 09:43:57
【问题描述】:

以这样的数组为例:

idx = [ 0xe, 0x3,  0x6, 0x8, 0x2 ]

我想获得 Objective C 中每个指定项的整数和字符串表示形式。我已经模拟了一个完美运行的 ruby​​ 示例:

0xe gives 14 when i run 0xe.to_i and "e" when i run to_i(base=16)
0x3 gives 3 when i run 0x3.to_i and gives 3 when i run to_i(base=16) 

如何在 Objective C 中实现这一点?

【问题讨论】:

  • 这些是非本地化数字吗?

标签: objective-c cocoa hex


【解决方案1】:

要获得十进制和十六进制等效项,您可以:

int number = 0xe; // or 0x3, 0x6, 0x8, 0x2

NSString * decimalString = [NSString stringWithFormat:@"%d", number];
NSString * hexString = [NSString stringWithFormat:@"%x", number];

【讨论】:

  • 谢谢,这有点帮助。但是我可以将 0xe 存储在 NSNumber 中吗?我不能将它分配给 int,因为我想将这些东西存储在 NSArray 中,因为你不能在其中使用标准 C 类型(可变与否)
  • NSNumber 可以包装任何原始数字类型。当然,一旦对数字进行字符串表示,就可以将字符串存储在数组中。
【解决方案2】:

一旦你有了一个 NSString,你就可以使用该类中的方法,比如 intValue 或 longValue 或 floatValue

【讨论】:

    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2015-11-29
    • 2012-10-02
    • 2014-12-15
    相关资源
    最近更新 更多