iOS - int (unsigned int) maximum value is 2147483647, unsigned int doesn't work?

int, integer, ios, unsigned

Solution

The problem is `intValue` which returns a `int` (not an `unsigned int`) and is maxed out at 2,147,483,647. If you need larger than `INT32_MAX`, then use `long` variables and `NSString` method `longLongValue` instead of `intValue`.

Yes, `%d` is signed, but if you use `%u` that will not solve the problem with `intValue`. Using `long long` variables and `longlongValue` method will solve this. For example:

NSString *string = @"2147483650";

unsigned int i = [string intValue];
NSLog(@"i = %u", i); // returns 2147483647

NSUInteger j = [string integerValue];
NSLog(@"j = %u", j); // returns 2147483647

long long k = [string longLongValue];
NSLog(@"k = %lld", k); // returns 2147483650

So, looking at your original code, it might be:

long long minNumber;

long long maxNumber;

long long ranNumber;

minNumber = [self.textFieldFrom.text longLongValue];
maxNumber = [self.textFieldTo.text longLongValue];

ranNumber = arc4random_uniform(maxNumber-minNumber+1) + minNumber;

NSString *str = [NSString stringWithFormat:@"%lld", ranNumber];

self.label.text = str;

Problem

the maximum value for an 32-Bit integer is: 2^31-1 = 2147483647. but just with negative and positive number. because the half of the number is negative. so the real maximum value is 2^32-1 = 4294967295. but in this case we just use positive numbers. ok, a normal int is both negative and positive number. i want to use just positive number because i want the maximum value to be: 4294967295. i'm going to use "unsigned int" instead of "int" but this will not work! the maximum value is still 2147483647. here is the code for a simple random number generator: ``` -(Action for my button) { unsigned int minNumber; unsigned int maxNumber; unsigned int ranNumber; minNumber=[self.textFieldFrom.text intValue]; //getting numbers from my textfields maxNumber=[self.textFieldTo.text intValue]; //Should i use unsigned intValue? ranNumber=rand()%(maxNumber-minNumber+1)+minNumber; NSString *str = [NSString stringWithFormat:@"%d", ranNumber]; self.label.text = str; } ``` and this will view : 2147483647 as a maximum value. what's wrong? should i use unsigned intValue when i getting numbers from my textFields? Jonathan here you can read about this number. : http://en.wikipedia.org/wiki/2147483647

Original source