Question

I've been declaring a class with a ulong parameter, but when I want ot assign it in the constructor, the program tells me, thata something is wrong, but I don't understand what is. It is a ulong type, I don't want him to convert anything.

public class new_class
{
    ulong data;
    new_class()
    {
        Random rnd = new Random();
        data = rnd.Next() * 4294967296 + rnd.Next(); //4294967296 = 2^32
    }
}

bonus points if you can tell me if this declaration of random ulong is correct, it should first randomize int (32 bits) and store them in first 32 bits of ulong, then do new random number and store them in the second 32 bits.

Was it helpful?

Solution

Random.Next() only generates 31 bits of true randomness:

A 32-bit signed integer greater than or equal to zero and less than MaxValue.

Since the result is always positive, the most significant bit is always 0.

You could generate two ints and combine them to get a number with 62 bits of randomness:

data = ((ulong)rnd.Next() << 32) + rnd.Next();

If you want 64 bits of randomness, another method is to generate 8 random bytes using GetBytes:

byte[] buffer = new byte[8];
rnd.NextBytes(buffer);
data = BitConverter.ToUInt64(buffer, 0);

OTHER TIPS

The problem here is that you're getting a long as the result of your expression. The error message should make that pretty clear:

Cannot implicitly convert type 'long' to 'ulong'. An explicit conversion exists (are you missing a cast?)

You'd have to explicitly cast the result to ulong to assign it to data, making it

data = ((ulong) ( rnd.Next() * 4294967296 + rnd.Next() ) ;

However, your intent would be clearer, though, if you were to simply shift bits:

ulong data = ( ((ulong)rng.Next()) << 32 )
           | ( ((ulong)rng.Next()) <<  0 )
           ;

It would also be faster as bit shifts are a much simpler operation than multiplication.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top