NSString转换为NSUInteger

14

我有一个NSString类型的数字@"15",我想把它转换成NSUInteger类型,但是我不知道怎么做...


1
如需请求从NSString读取无符号值的支持,请访问http://bugreport.apple.com并针对组件“Foundation | X”提交radar:// 2264733的副本。 - Quinn Taylor
4个回答

26
NSString *str = @"15";
// Extract an integer number, returns 0 if there's no valid number at the start of the string.
NSInteger i = [str integerValue];

如果你真的需要一个NSUInteger,只需将其强制转换,但你可能希望在此之前测试一下该值。


2
有点不完整。如果值大于INT_MAX,这将无法工作。如果您将其用于字节长度之类的事情,那么这很可能会发生。 - Corey Floyd
3
将其转换为NSUInteger(如上所述)看起来像NSUInteger i =(NSUInteger)[str integerValue]; - captainpete
这对于许多大数值是行不通的。例如,对于此字符串:@18140419601393549482",您将得到9223372036854775807,这不是您想要的结果。对我来说,无论是intValue、integerValue还是longLongValue都不能给出正确的答案。 - Motti Shneor

21

目前选择的答案对于NSUInteger是不正确的。正如Corey Floyd在所选答案的评论中指出的那样,如果该值大于INT_MAX,则此方法将无效。更好的方法是使用NSNumber,然后使用NSNumber上的方法之一来检索您感兴趣的类型,例如:

NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;

请在您的评论中更加详细,hasan83。您到底做了什么事情没有成功? - Zach Dennis
一个适合于 nsuinteger 但不适合于 nsinteger 的值发生了转换。 - hasan

9

在64位系统上,所有这些答案都是错误的。

NSScanner *scanner = [NSScanner scannerWithString:@"15"];
unsigned long long ull;
if (![scanner scanUnsignedLongLong:&ull]) {
  ull = 0;  // Or handle failure some other way
}
return (NSUInteger)ull;  // This happens to work because NSUInteger is the same as unsigned long long at the moment.

测试9223372036854775808,这将无法适应有符号的long long


谢谢,这是唯一一个适用于我的(相当大的)MD5号码 - @18140419601393549482的解决方案。顺便问一下,是否有类似于“NSScanner”的对象可以在C缓冲区中处理原始数据? NSScanner似乎只能处理NSString对象。我想节省一次转换... - Motti Shneor

0

你可以尝试使用 [string longLongValue] 或者 [string intValue]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接