'How do I generate big random numbers in Dart?

The normal Dart Random class supports Random values up to (1 << 32) - 1, which is indeed quite big, but how can I generate numbers, which are much larger than this? (With much larger I mean ((1 << 32) - 1) * 10^50 or something like that.



Solution 1:[1]

You can do this by combining multiple random numbers; for example if you want a 64bit random number, you could do:

var r = new Random();
var random1 = r.nextInt(pow(2, 32));
var random2 = r.nextInt(pow(2, 32));
var bigRandom = (random1 << 32) | random2;
print(bigRandom); // 64bit random number

Be aware; if you're running outside of the Dart VM (using dart2js), then you'll be bound by JavaScripts number restrictions. If you need rally big numbers in JavaScript, you'll need a library (and the performance will likely suck).

Solution 2:[2]

Here is my implementation in case someone needs it in the future:

class BigRandom {
  static final rnd = new Random();

static int nextInt(int max) {
if (max > pow(2, 32)) {
  var charCount = max.toString().length;
  var seperator = (charCount / 2).floor();

  var leftHalf = int.parse(max.toString().substring(0, seperator));
  var rightHalf = int.parse(max.toString().substring(seperator));

  var rndLeft = nextInt(leftHalf);
  var rndRight = nextInt(rightHalf);
  return int.parse('$rndLeft$rndRight');
} else {
  return rnd.nextInt(max);
}
}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Danny Tuppeny
Solution 2 Schotti100