Redzen.Numerics.XorShiftRandom.NextBytes C# (CSharp) Method

NextBytes() public method

Fills the provided byte array with random bytes. This method is functionally equivalent to System.Random.NextBytes().
public NextBytes ( byte buffer ) : void
buffer byte
return void
        public void NextBytes(byte[] buffer)
        {
            // Fill up the bulk of the buffer in chunks of 4 bytes at a time.
            uint x=_x, y=_y, z=_z, w=_w;
            int i=0;
            uint t;
            for(int bound=buffer.Length-3; i<bound;)
            {
                // Generate 4 bytes.
                // Increased performance is achieved by generating 4 random bytes per loop.
                // Also note that no mask needs to be applied to zero out the higher order bytes before
                // casting because the cast ignores thos bytes. Thanks to Stefan Troschütz for pointing this out.
                t = x^(x<<11);
                x=y; y=z; z=w;
                w=(w^(w>>19))^(t^(t>>8));

                buffer[i++] = (byte)w;
                buffer[i++] = (byte)(w>>8);
                buffer[i++] = (byte)(w>>16);
                buffer[i++] = (byte)(w>>24);
            }

            // Fill up any remaining bytes in the buffer.
            if(i < buffer.Length)
            {
                // Generate 4 bytes.
                t = x^(x<<11);
                x=y; y=z; z=w;
                w=(w^(w>>19))^(t^(t>>8));

                buffer[i++] = (byte)w;
                if(i < buffer.Length)
                {
                    buffer[i++]=(byte)(w>>8);
                    if(i < buffer.Length)
                    {
                        buffer[i++] = (byte)(w>>16);
                        if(i < buffer.Length)
                        {
                            buffer[i] = (byte)(w>>24);
                        }
                    }
                }
            }
            _x=x; _y=y; _z=z; _w=w;
        }

Usage Example

Example #1
0
 public void NextBytes()
 {
     int sampleCount = 10000000;
     XorShiftRandom rng = new XorShiftRandom();
     byte[] sampleArr = new byte[sampleCount];
     rng.NextBytes(sampleArr);
     NextByteInner(sampleArr);
 }
All Usage Examples Of Redzen.Numerics.XorShiftRandom::NextBytes