C # Random (long)

I am trying to create a seed based number in C #. The only problem is that the seed is too big to be int32. Is there a way to use a long seed?

And yes, the seed MUST be long.

+5
source share
2 answers

Here is the C # version Java.Util.Randomthat I ported from the Java specification .

It’s best to write a Java program to generate number loading and verify that this version of C # generates the same numbers.

public sealed class JavaRng
{
    public JavaRng(long seed)
    {
        _seed = (seed ^ LARGE_PRIME) & ((1L << 48) - 1);
    }

    public int NextInt(int n)
    {
        if (n <= 0)
            throw new ArgumentOutOfRangeException("n", n, "n must be positive");

        if ((n & -n) == n)  // i.e., n is a power of 2
            return (int)((n * (long)next(31)) >> 31);

        int bits, val;

        do
        {
            bits = next(31);
            val = bits % n;
        } while (bits - val + (n-1) < 0);
        return val;
    }

    private int next(int bits)
    {
        _seed = (_seed*LARGE_PRIME + SMALL_PRIME) & ((1L << 48) - 1);
        return (int) (((uint)_seed) >> (48 - bits));
    }

    private long _seed;

    private const long LARGE_PRIME = 0x5DEECE66DL;
    private const long SMALL_PRIME = 0xBL;
}
+2
source

I would take advantage of @Dyppl's answer provided here: Random number in the far distance, is that so?

, , :

long LongRandom(long min, long max, Random rand) 
{
    byte[] buf = new byte[8];
    rand.NextBytes(buf);
    long longRand = BitConverter.ToInt64(buf, 0);
    return (Math.Abs(longRand % (max - min)) + min);
}

:

long r = LongRandom(100000000000000000, 100000000000000050, new Random());
0

All Articles