Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 8-byte number in Java

Tags:

java

I'm a little bit confused, how to do this. I know I can use Random class to generate random numbers, but I don't know how to specify and generate 8-byte number?

Thanks, Vuk

like image 451
Vuk Avatar asked Dec 25 '10 21:12

Vuk


People also ask

How to generate random bytes in Java?

The java. util. Random. nextBytes() method generates random bytes and provides it to the user defined byte array.

How do you make random bytes?

To create a single random byte, it calls the Math. random() * 256 function. This creates a random floating point number in the range from 0 to 255.

How do you generate a random hexadecimal in Java?

To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java. util. Random. nextInt() and then it can be converted to hexadecimal form using Integer.

How do you generate random bytes in Python?

urandom() method is used to generate a string of size random bytes suitable for cryptographic use or we can say this method generates a string containing random characters. Return Value: This method returns a string which represents random bytes suitable for cryptographic use.


1 Answers

You should note that the java.util.Random class uses a 48-bit seed, so not all 8-byte values (sequences of 64 bits) can be generated using this class. Due to this restriction I suggest you use SecureRandom and the nextBytes method in this situation.

The usage is quite similar to the java.util.Random solution.

SecureRandom sr = new SecureRandom();
byte[] rndBytes = new byte[8];
sr.nextBytes(rndBytes);

Here is the reason why a 48-bit seed is not enough:

  • The Random class implements a pseudo random generator which means that it is deterministic.
  • The current "state" of the Random determines the future sequence of bits.
  • Since it has 248 states, it can't have more than 248 possible future sequences.
  • Since an 8-byte value has 264 different possibilities, some of these possibilities will never be read from the Random object.

Based on @Peter Lawreys excellent answer (it deserves more upvotes!): Here is a solution for creating a java.util.Random with 2×48-bit seed. That is, a java.util.Random instance capable of generating all possible longs.

class Random96 extends Random {
    int count = 0;
    ExposedRandom extra48bits;

    class ExposedRandom extends Random {
        public int next(int bits) {    // Expose the next-method.
            return super.next(bits);
        }
    }

    @Override
    protected int next(int bits) {
        if (count++ == 0)
            extra48bits = new ExposedRandom();
        return super.next(bits) ^ extra48bits.next(bits) << 1;
    }
}
like image 74
aioobe Avatar answered Sep 25 '22 14:09

aioobe