0

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.

Robbo_UK
  • 11,351
  • 25
  • 81
  • 117
  • 1
    they are bit operations. Check out this article https://www.baeldung.com/java-bitwise-operators – Morph21 Mar 29 '22 at 12:36
  • See also my explanation on randomness of UUID https://stackoverflow.com/questions/7532807/are-java-random-uuids-predictable/7532965#7532965 – Robert Mar 29 '22 at 12:43
  • Bitwise OR is used to guarantee particular bits are 1. Bitwise AND is used to guarantee particular bits are 0. (This practice goes back many decades.) – VGR Mar 29 '22 at 16:07

0 Answers0