user2526811
user2526811

Reputation: 1253

arc4random() gives negative Number in iOS

Sometime arc4random() gives negative number also in objective C.

My code is as follow:

Try 1:

long ii = arc4random();

Try 2:

int i = arc4random();

How can I only get positivite random number?

Thank you,

Upvotes: 0

Views: 319

Answers (2)

swiftBoy
swiftBoy

Reputation: 35783

You should use the arc4random_uniform() function. this is the most common random function used.

arc4random_uniform() function

Returns a random number between 0 and the inserted parameter minus 1. For example arc4random_uniform(3) may return 0, 1 or 2 but not 3.

Example

u_int32_t randomPositiveNo = arc4random_uniform(5) + 1; //to get the range 1 - 5

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

No, it's always positive as it returns an unsigned 32-bit integer (manpage):

u_int32_t arc4random(void);

You are treating it as a signed integer, which is incorrect.

Upvotes: 4

Related Questions