2

I need to generate random 4-byte length number in Java.

I came to this:

Random rnd = new Random();
int i = 0;

while((i=rnd.nextInt()) < 0x1000000){}
return i;

where 0x1000000 - is 3-byte value, and int is 4-byte according to JLS.

Are there any better solutions?

UPD: Yes, by "4-byte length" number I mean a 4-byte number with MSB (most significant byte)

glaz666
  • 8,707
  • 19
  • 56
  • 75
  • See: http://stackoverflow.com/questions/5683206/how-to-create-an-array-of-20-random-bytes – rethab May 27 '13 at 14:00
  • 2
    You mean the MSB of the number is not supposed to be 0? – Mr Lister May 27 '13 at 14:00
  • 1
    [SecureRandom.nextBytes()](http://docs.oracle.com/javase/6/docs/api/java/security/SecureRandom.html#nextBytes(byte[])) – Sergey Kalinichenko May 27 '13 at 14:02
  • What's wrong with [Random#nextInt](http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt%28%29)? Quote: "All 2^32 possible int values are produced with (approximately) equal probability." – devconsole May 27 '13 at 14:14

2 Answers2

3

A "4-byte length number" is slightly incorrect-confusing spec. You mean a random number uniformly distributed in the range of 0 2^32-1 (which fits in 4 bytes -unsigned) ? How about rnd.nextInt() ?

leonbloy
  • 73,180
  • 20
  • 142
  • 190
2

If the most significant byte is suppose to not be equal to 0 but others linearly distributed then something like that should work:

 Random rnd = new Random();
 int result = (rnd.nextInt(0xFF) + 1) << 8*3;
 result += rnd.nextInf(0x1000000);

If the value can take any number then as othes pointed out there is Random.nextBytes or Random.nextInt (my understanding of documentation is, however, that it can return any value including 0).

What is the purpose of this number? If you generate key then usually the first bit should be 1 (and SecureRandom used) - and probably, unless you are world-class cryptographer, you should not write the algorithm but use (preferably high-level) library.

Maciej Piechotka
  • 7,028
  • 6
  • 39
  • 61