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...
NSString to NSUInteger
Asked Answered
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.
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
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;
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
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
.
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
you can try with [string longLongValue]
or [string intValue]
..
© 2022 - 2024 — McMap. All rights reserved.
Foundation | X
. – Haileyhailfellowwellmet