Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a random 256 bit integer in Dart?

Tags:

math

dart

I would like to create a random (uniformly distributed) 256bit integer in Dart. Dart's Random only support 32 bit integers. Any ideas?

like image 507
gmosx Avatar asked Apr 26 '13 08:04

gmosx


1 Answers

import "dart:math";

// 16bit, because random.nextInt() only supports (2^32)-1 possible values.
const PARTS = 16;  // 256bit / 16bit

void main() {
  Random rand = new Random();
  int combinedVal = 0;
  // random parts
  for(var i=0;i<PARTS;i++) {
    int part = rand.nextInt(1<<16); // 2^16
    print("Part $i: $part");
    // shift the 16bit blocks to the left and append the new block
    combinedVal <<= 16;
    combinedVal += part;
    print("Combined: $combinedVal");
  }
  print("Final Result: $combinedVal");
}

Output (console application):

Part 0: 4273569419
Combined: 4273569419
Part 1: 2298770505
Combined: 18354840894089491529
Part 2: 1076269765
Combined: 78833441363397765815400305349
Part 3: 500743884
Combined: 338587052486927055616611084622869610188
Part 4: 1660193956
Combined: 1454220317280387171410917722806313469431388605604
Part 5: 1335995533
Combined: 6245828703898006563427837796799909693532109776937558322317
Part 6: 2409230726
Combined: 26825630019660005909515912993248305589473794217828668028446551175558
Part 7: 3743170719
...

EDIT

As Darshan Computing pointed out in the comments, to make this work with dart2js, some modifications are needed, and this would result in lost precision. To use this with browser, an external library and js interop would be needed. As an example, i used Leemon Baird's public domain BigInt library

HTML file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Web Playground</title>
    <link rel="stylesheet" href="web_playground.css">
    <script src="BigInt.js"></script> <!-- this is the important part -->
  </head>
  <body>
    <h1>Web Playground</h1>
    <script type="application/dart" src="web_playground.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

Dart file:

import "dart:html";
import "package:js/js.dart" as js;

void main() {
  var rand = js.context.randBigInt(256,0);
  window.alert(js.context.bigInt2str(rand,10));
}
like image 142
MarioP Avatar answered Nov 15 '22 07:11

MarioP