Search code examples
javarandombitwise-and

in Random.java, isn't x&((1L<<48)-1)==x?


See int next(int bits) from http://developer.classpath.org/doc/java/util/Random-source.html. It contains the line

seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);

The number (1L<<48)-1 is 1111111111111111111111111111111111111111111111111111111111111111. Does and'ing it with a number do anything? Is this a quirk with signed longs? Is this old outdated code?


Solution

  • It isn't 64 ones:

    1111111111111111111111111111111111111111111111111111111111111111
    

    It's 48 ones:

    0000000000000000111111111111111111111111111111111111111111111111
    

    ANDing with this number clears the leftmost 16 bits.