4

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..

Taryn
  • 242,637
  • 56
  • 362
  • 405
jianzaixian
  • 243
  • 3
  • 5
  • possible duplicate of [Very Large Numbers in Java Without using java.math.BigInteger](http://stackoverflow.com/questions/5318068/very-large-numbers-in-java-without-using-java-math-biginteger) – Damian Leszczyński - Vash Oct 07 '12 at 11:19

2 Answers2

8

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.

4

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.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53