NSString to NSUInteger
Asked Answered
S

4

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...

Sporades answered 1/5, 2010 at 11:24 Comment(1)
To request support for reading unsigned values from NSString, please visit bugreport.apple.com and file a dupe of radar://2264733 against component Foundation | X.Haileyhailfellowwellmet
S
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.

Skill answered 1/5, 2010 at 11:30 Comment(3)
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.Advent
Casting it to an NSUInteger (as mentioned) would look like NSUInteger i = (NSUInteger)[str integerValue];Applicative
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.Hophead
C
20

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;
Candleberry answered 1/4, 2014 at 20:16 Comment(2)
Please be more descriptive in your comment hasan83. What exactly did you do that didn't work?Candleberry
a value that fits in nsuinteger but not in nsinteger did get converted.Unmentionable
O
8

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.

Obstetrics answered 6/1, 2016 at 19:8 Comment(1)
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...Hophead
A
0

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

Annulus answered 1/5, 2010 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.