0

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Vasu N
  • 344
  • 1
  • 2
  • 9
  • 2
    `return -(NSInteger)random;`. The issue is because of 64 bits and 32 bits architectures, and the `NSInteger` hasn't the same definition. And you are doing the `-` sutff, on the random, and the casting. – Larme Mar 03 '17 at 10:50

2 Answers2

2

You get negative numbers with

return -(NSInteger)random;

You need first to cast to a signed type.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Probably would be good to explain why this is the case (i.e. negating an unsigned number will return an unsigned number so you need to convert to signed first). – Itai Ferber Mar 03 '17 at 16:19
0

This will surely help....

-(int) generateRandomNumberWithlowerBound:(int)0
                               upperBound:(int) 2147483647
{
    int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
    return -(NSInteger)(rndValue);
}
Ravindra Shekhawat
  • 4,275
  • 1
  • 19
  • 26