How to generate random number from 0 to 2 ^ 32-1 in java

how to create random number between 0 and 2^32-1 in java? I am writing a link:

 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 he prints

 -1161730240 -1387884711 -3808952878 -3048911995 -2135413666 

I do not know why..

+4
source share
2 answers

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

 (long)(1<<31) 

interprets the value 1 as int, shifts it by 31 bits, which makes it the largest negative int, and then it is discarded for a long (still negative).

Do you want to

 (1L << 31) 

how is your displacement.

+4
source

If you want 0 to 2 ^ 32-1, 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 need. To get around this, you use long , which has 64 bits and can take values ​​in the required range.

+7
source

Source: https://habr.com/ru/post/1438249/


All Articles