0

I am trying to convert from python to C#

python:

rand = random.randint(0, 2 ** 50)

and here's what I did in C#

var value = Math.Pow(2, 50);
var result = random.Next(0, Convert.ToInt32(value));

I'm getting this error

Unhandled exception. System.OverflowException: Value was either too large or too small for an Int32.
   at System.Convert.ToInt32(Double value)

I wanted to generate from range 0 to value

mark12345
  • 233
  • 1
  • 4
  • 10

1 Answers1

3

In C#, an int is 32 bits. You have 2^50, that needs 50 bits. It will always be too large.

You could use Convert.ToInt64(value), that would fit but Random only returns an Int32. So it is kind of pointless.

I would suggest using 2^30. You're not going to get any more range. That 50 looks kind of arbitrary anyway.

var value = Math.Pow(2, 30);

On second thought, just use

var result = random.Next();  // returns 0 .. Int32.MaxValue-1

and remove everything with value.

H H
  • 263,252
  • 30
  • 330
  • 514