简体   繁体   中英

Is there a simple way to invert an integer function that experiences overflow?

I'm trying to create an inverse function for the java.util.Random setSeed and next functions. Essentially I want to be able to input a long value (before it's truncated to 48 bits) and get back a seed or family of seeds that will result in that value for the first nextLong() call. Its relevant source code is below:

setSeed(long seed)

seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)

next(int bits)

//this function is called by nextLong()
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)

The problem seems to occur because of the second part, as the integer overflows after the multiplication. Because of this, I can't simply divide out the constant as it will end up with a different result and will NOT give me the correct seed.

I'm not very experienced in binary operations and was wondering if there's a way to account for this overflow when dividing to obtain the correct seed without having to guess what the really big post-multiplication number actually was.

Wondering if what you really want is a random number generator, where the first number generated is a specific value.

class MyRandom extends java.util.Random {
    long targetValue;
    long offset;
    int count=0;

    public MyRandom(long target) {
        this.targetValue = target;
   } 

   public long nextLong() {
        long rnd = super.nextLong();
        if(count++==0) {
            offset = target - rnd;
        }
        return rnd + offset;
   }
}

On the first call to nextLong it will set the offset and return target. On all calls it will return the random number shifted by a fixed amount. This should give a uniform distribution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM