Reputation: 352
I'm trying to generate random negative NSInteger using the following code,
+ (NSInteger)getNegativeRandomNumber {
uint32_t random = arc4random_uniform(2147483647); // where 2147483647 is the max 32-bit positive value returned by random function
return (NSInteger)(-1 * random); // convert the positive into negative number
}
But occasionally this code gives me positive numbers. Do you see any issue with this code?
Upvotes: 0
Views: 541
Reputation: 4363
This will surely help....
-(int) generateRandomNumberWithlowerBound:(int)0
upperBound:(int) 2147483647
{
int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
return -(NSInteger)(rndValue);
}
Upvotes: 0
Reputation: 285180
You get negative numbers with
return -(NSInteger)random;
You need first to cast to a signed type.
Upvotes: 2