Search code examples
javalong-integerxorboolean-operations

XOR being used to compare longs in Random class?


I decompiled the Random class using IntelliJ IDEA and I found this line:

public Random() {
    this(seedUniquifier() ^ System.nanoTime());
}

I am confused because I thought the ^ symbol was an XOR that only compared two boolean values. The two methods, seedUniquifier(), and System.nanoTime() both return long values.

private static long seedUniquifier() {
    long var0;
    long var2;
    do {
        var0 = seedUniquifier.get();
        var2 = var0 * 181783497276652981L;
    } while(!seedUniquifier.compareAndSet(var0, var2));

    return var2;
}

Solution

  • The ^ (XOR) operator in Java applies to either two booleans, two ints, or two longs, giving back the same type as a result.

    I assume you know how XOR works on two Boolean values, which can be true or false.

    When XOR is applied to two integers, the XOR is applied separately to each bit. For example:

    0xC5 = 1 1 0 0 0 1 0 1
    0xF9 = 1 1 1 1 1 0 0 1
    ---------------------- XOR
    0x3C = 0 0 1 1 1 1 0 0