1 year ago

#349345

test-img

Robbo_UK

RandomUUID in UUID operators code explanation

I'm looking to understand the following operators

  • &= 0x0f /* clear version */
  • |= 0x40 /* set to version 4 */
  • &= 0x3f /* clear variant */
  • |= 0x80. /* set to IETF variant */

Found in the following code UUID native java class

public static UUID randomUUID() {
        SecureRandom ng = Holder.numberGenerator;

        byte[] randomBytes = new byte[16];
        ng.nextBytes(randomBytes);
        randomBytes[6]  &= 0x0f;  /* clear version        */
        randomBytes[6]  |= 0x40;  /* set to version 4     */
        randomBytes[8]  &= 0x3f;  /* clear variant        */
        randomBytes[8]  |= 0x80;  /* set to IETF variant  */
        return new UUID(randomBytes);
    }

My understanding is that it creates 16 random numbers puts them into an array and then on the 5th and 7th item in that array it applies some operations on it. I'm not following what those operations are as I have not seen &= and | used like this before nor the hexidecimal codes?. Any pointers much appreciated.

java

operators

uuid

secure-random

0 Answers

Your Answer

Accepted video resources