jianzaixian
jianzaixian

Reputation: 253

how to generate random number between 0 and 2^32-1 in java

how to generate random number between 0 and 2^32-1 in java? I write link this:

long[]num = new long[size + 1];
Random random = new Random();
for (int i = 1; i < size + 1; i++) {
num[i] = (long)random.nextInt()+(long)(1<<31);
System.out.println(num[i]);
}

but it print

-1161730240
-1387884711
-3808952878
-3048911995
-2135413666

i don't know why..

Upvotes: 4

Views: 5658

Answers (2)

user520288
user520288

Reputation:

If you want from 0 to 2^32-1, then you should use Random.nextLong() & 0xffffffffL instead of Random.nextInt().

Java does not support unsigned types which means that your int cannot take values in the range you want. To get around this, you use a long which is 64bits and can take values in the needed range.

Upvotes: 8

Roger Lindsj&#246;
Roger Lindsj&#246;

Reputation: 11553

Your problem is where you try to add an offset to avoid negative numbers.

(long)(1<<31)

interprets the 1 as an int, shifts it 31 bits which makes it the largest negative int, and then it it casted to a long (still negative).

You want

(1L << 31)

as your offset.

Upvotes: 4

Related Questions