14

I've got a number in a NSString @"15". I want to convert this to NSUInteger, but I don't know how to do that...

Eimantas
  • 48,927
  • 17
  • 132
  • 168
dododedodonl
  • 4,585
  • 6
  • 30
  • 43
  • 1
    To request support for reading unsigned values from NSString, please visit http://bugreport.apple.com and file a dupe of radar://2264733 against component `Foundation | X`. – Quinn Taylor Jan 23 '13 at 21:46

4 Answers4

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];

If you really want an NSUInteger, just cast it, but you may want to test the value beforehand.

squelart
  • 11,261
  • 3
  • 39
  • 43
  • 2
    A little incomplete. This won't work if the value is larger than INT_MAX. And if this is quite likely if you are using it for things like byte lengths. – Corey Floyd Oct 15 '10 at 07:45
  • 3
    Casting it to an NSUInteger (as mentioned) would look like `NSUInteger i = (NSUInteger)[str integerValue];` – captainpete Oct 27 '11 at 00:32
  • This won't work for many large numbers. For this string, for example: @18140419601393549482" you will get: 9223372036854775807 which isn't what you want. For me, neither intValue, integerValue or even longLongValue gives the right answer. – Motti Shneor Nov 20 '22 at 13:10
21

The currently chosen answer is incorrect for NSUInteger. As Corey Floyd points out a comment on the selected answer this won't work if the value is larger than INT_MAX. A better way of doing this is to use NSNumber and then using one of the methods on NSNumber to retrieve the type you're interested in, e.g.:

NSString *str = @"15"; // Or whatever value you want
NSNumber *number = [NSNumber numberWithLongLong: str.longLongValue];
NSUInteger value = number.unsignedIntegerValue;
Zach Dennis
  • 1,754
  • 15
  • 19
9

All these answers are wrong on a 64-bit system.

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.

Test with 9223372036854775808, which won't fit in a signed long long.

George
  • 4,189
  • 2
  • 24
  • 23
  • Thank you, this is the only solution that worked with my (rather large) MD5 number - @18140419601393549482" BTW is there an "NSScanner"-like object that will work on raw data in a C-buffer? NSScanner seems only to work on NSString objects. I'd like to save one conversion... – Motti Shneor Nov 20 '22 at 13:30
0

you can try with [string longLongValue] or [string intValue]..

Jack
  • 131,802
  • 30
  • 241
  • 343