BigInt

suggest change

Dart's int has a fixed size. On the Dart VM and in native executables it is a 64-bit two's complement integer, and when it overflows it wraps around without any error. When compiled to JavaScript, int is a JavaScript number and is only exact up to 2^53.

BigInt from dart:core is an arbitrary-precision integer. It grows as needed, so it never overflows and never loses digits. You don't need to import anything to use it.

This article covers:

The examples were run with Dart 3.13.

Why you need BigInt

The largest 64-bit int is 9223372036854775807. Adding one to it wraps around to the smallest value:

void main() {
  const max = 9223372036854775807;
  print(max);
  print(max + 1);
  print(BigInt.from(max) + BigInt.one);
}
9223372036854775807
-9223372036854775808
9223372036854775808

Typical reasons to use BigInt:

For everything else, use int: it is much faster (see Performance).

Creating BigInt values

There are no BigInt literals. You create values from an int, a double or a string:

void main() {
  final a = BigInt.from(42);
  final b = BigInt.parse('123456789012345678901234567890');
  final c = BigInt.parse('ff' * 10, radix: 16);
  final d = BigInt.parse('-0x1F');
  print([a, b, c, d]);

  print(BigInt.tryParse('12x'));
  print(BigInt.tryParse('  77  '));

  print(BigInt.from(1e20));
  print(BigInt.from(3.99));
  print(BigInt.from(-3.99));
  try {
    BigInt.from(double.infinity);
  } catch (e) {
    print(e);
  }

  print([BigInt.zero, BigInt.one, BigInt.two]);
}
[42, 123456789012345678901234567890, 1208925819614629174706175, -31]
null
77
100000000000000000000
3
-3
Invalid argument(s): Value must be finite: Infinity
[0, 1, 2]

Things to know:

Always parse large values from a string. Writing them as an int literal doesn't work, because the literal itself must fit in an int.

Arithmetic

BigInt supports the usual operators. Both operands must be BigInt:

void main() {
  final x = BigInt.parse('100000000000000000000');
  final y = BigInt.from(7);

  print(x + y);
  print(x - y);
  print(x * y);
  print(x ~/ y); // integer division
  print(x % y); // modulo
  print(x.remainder(y));
  print(x / y); // returns a double!
  print((x / y).runtimeType);

  print(BigInt.two.pow(100));
  print(-x);
  print((-x).abs());
  print((-x).sign);
}
100000000000000000007
99999999999999999993
700000000000000000000
14285714285714285714
2
2
14285714285714287000.0
double
1267650600228229401496703205376
-100000000000000000000
100000000000000000000
-1

Note that the / operator returns a double, so the result is rounded to about 16 significant digits. To stay exact, use ~/ and % (or remainder).

Division and negative numbers

The three division-related operations differ for negative numbers:

void main() {
  final a = BigInt.from(-7);
  final b = BigInt.from(3);

  print(a ~/ b); // truncates toward zero
  print(a % b); // always non-negative (Euclidean modulo)
  print(a.remainder(b)); // has the sign of the dividend

  try {
    print(a ~/ BigInt.zero);
  } on IntegerDivisionByZeroException catch (e) {
    print(e);
  }
}
-2
2
-1
IntegerDivisionByZeroException

This matches how int behaves. % is what you want for modular arithmetic; remainder pairs with ~/ so that (a ~/ b) * b + a.remainder(b) == a.

pow() takes an int exponent and throws an ArgumentError if it's negative.

Comparison and collections

BigInt implements Comparable<BigInt> and the <, <=, >, >= operators. Equality is by value and hashCode is consistent with it, so BigInt works as a map key or in a set:

void main() {
  final x = BigInt.parse('100000000000000000000');
  final y = BigInt.from(7);

  print(x > y);
  print(x.compareTo(y).sign);
  print(BigInt.from(5) == BigInt.parse('5'));
  print(identical(BigInt.from(5), BigInt.parse('5')));

  final huge = BigInt.two.pow(64) + BigInt.from(5);
  final names = {huge: 'big'};
  print(names[BigInt.parse('18446744073709551621')]);

  final list = [BigInt.from(30), BigInt.parse('1' * 25), BigInt.from(-4)];
  list.sort();
  print(list);
  print(list.reduce((a, b) => a + b));
  print(list.reduce((a, b) => a > b ? a : b));
}
true
1
true
false
big
[-4, 30, 1111111111111111111111111]
1111111111111111111111137
1111111111111111111111111

compareTo() only promises the sign of its result: it returned 2 here, not 1. Compare it with zero (or take .sign) rather than testing for 1 or -1.

list.sort() works without a comparator because BigInt is Comparable. dart:math's max() and min() only accept num, so use reduce as shown.

See Equality and comparison for more on ==, hashCode and Comparable.

Mixing BigInt with int

There is no implicit conversion between int and BigInt. BigInt is not a num, and both of these are compile errors:

void main() {
  final n = BigInt.from(1000);
  print(n + 1);
  print(1 + BigInt.one);
}
mix.dart:3:13: Error: A value of type 'int' can't be assigned to a variable of type 'BigInt'.
 - 'BigInt' is from 'dart:core'.
  print(n + 1);
            ^
mix.dart:4:20: Error: A value of type 'BigInt' can't be assigned to a variable of type 'num'.
 - 'BigInt' is from 'dart:core'.
  print(1 + BigInt.one);
                   ^

Wrapping every number in BigInt.from() gets noisy. A small extension makes it shorter:

extension IntToBigInt on int {
  BigInt get big => BigInt.from(this);
}

void main() {
  final n = BigInt.parse('1000');
  print(n + 1.big);
  print(n * 3.big);
}
1001
3000

Converting to int, double and strings

void main() {
  final small = BigInt.from(123456);
  print(small.isValidInt);
  print(small.toInt() + 1);

  final huge = BigInt.two.pow(64) + BigInt.from(5);
  print(huge.isValidInt);
  print(huge.toInt()); // clamped on the VM
  print((-BigInt.two.pow(70)).toInt());

  print(huge.toDouble());
  print(BigInt.from(10).pow(400).toDouble());

  print(huge.toString());
  print(huge.toRadixString(16));
  print(huge.toRadixString(2));
  print(BigInt.from(255).toRadixString(36));

  print(huge.bitLength);
  print(BigInt.from(255).bitLength);
  print(huge.isEven);
  print(huge.isNegative);
}
true
123457
false
9223372036854775807
-9223372036854775808
18446744073709552000.0
Infinity
18446744073709551621
10000000000000005
10000000000000000000000000000000000000000000000000000000000000101
73
65
8
false
false

Always check isValidInt before calling toInt(). A value that doesn't fit doesn't throw; on the VM it is clamped to the int range, which silently gives a wrong answer. toDouble() rounds to the nearest double and returns Infinity if the value is too large.

bitLength is the number of bits needed to store the value without a sign bit. It's useful for working out how many bytes a number needs, as in the next section.

Formatting with thousands separators

toString() doesn't add grouping separators, and NumberFormat from package:intl only accepts num. A small helper works for any size:

String withSeparators(BigInt n) {
  final s = n.abs().toString();
  final out = StringBuffer(n.isNegative ? '-' : '');
  for (var i = 0; i < s.length; i++) {
    if (i > 0 && (s.length - i) % 3 == 0) out.write(',');
    out.write(s[i]);
  }
  return out.toString();
}

void main() {
  print(withSeparators(BigInt.two.pow(100)));
  print(withSeparators(-BigInt.from(1234567)));
  print(withSeparators(BigInt.from(999)));
}
1,267,650,600,228,229,401,496,703,205,376
-1,234,567
999

Bitwise operations

&, |, ^, ~, << and >> work like they do on int, treating negative numbers as if they had an infinite two's complement representation:

void main() {
  final a = BigInt.parse('f0f0', radix: 16);
  final b = BigInt.parse('ff00', radix: 16);

  print((a & b).toRadixString(16));
  print((a | b).toRadixString(16));
  print((a ^ b).toRadixString(16));
  print(~BigInt.zero);
  print(BigInt.one << 100);
  print((BigInt.one << 100) >> 98);
  print(BigInt.from(-1) >> 10);
}
f000
fff0
ff0
-1
1267650600228229401496703205376
4
-1

Shifting left never overflows, so BigInt.one << n is a quick way to compute 2^n.

Unsigned 64-bit values

Other systems often use unsigned 64-bit integers: a BIGINT UNSIGNED column in MySQL, a 64-bit hash, a Twitter-style snowflake ID. Values above 2^63 - 1 don't fit in Dart's signed int.

toUnsigned(width) and toSigned(width) reinterpret the lowest width bits:

void main() {
  // All 64 bits set, as stored in a signed int.
  const raw = -1;
  print(BigInt.from(raw).toUnsigned(64));

  final u64 = BigInt.parse('12345678901234567890');
  print(u64.isValidInt);

  // Store it in an int (same bits, different meaning)...
  final asInt = u64.toSigned(64).toInt();
  print(asInt);

  // ...and get the unsigned value back.
  print(BigInt.from(asInt).toUnsigned(64));

  print(BigInt.from(300).toUnsigned(8));
  print(BigInt.from(200).toSigned(8));
}
18446744073709551615
false
-6101065172474983726
12345678901234567890
44
-56

This round trip lets you keep a compact int in memory or in a Uint64List/Int64List and only use BigInt when you need to print or compare the unsigned value.

Converting to and from bytes

There is no built-in conversion between BigInt and bytes, but it only takes a few lines with shifts and masks. This version uses big-endian order (most significant byte first), which is what most protocols and crypto formats use:

import 'dart:typed_data';

BigInt bytesToBigInt(List<int> bytes) {
  var result = BigInt.zero;
  for (final b in bytes) {
    result = (result << 8) | BigInt.from(b);
  }
  return result;
}

Uint8List bigIntToBytes(BigInt value) {
  if (value.isNegative) throw ArgumentError('negative value');
  final length = (value.bitLength + 7) >> 3;
  final bytes = Uint8List(length);
  final mask = BigInt.from(0xff);
  for (var i = length - 1; i >= 0; i--) {
    bytes[i] = (value & mask).toInt();
    value >>= 8;
  }
  return bytes;
}

These two functions are used in the RSA example below. For hex strings, BigInt.parse(hex, radix: 16) and toRadixString(16) are simpler; see Base64 and hex encoding.

Big results: factorials and Fibonacci numbers

BigInt factorial(int n) {
  var result = BigInt.one;
  for (var i = 2; i <= n; i++) {
    result *= BigInt.from(i);
  }
  return result;
}

BigInt fibonacci(int n) {
  var a = BigInt.zero, b = BigInt.one;
  for (var i = 0; i < n; i++) {
    (a, b) = (b, a + b);
  }
  return a;
}

void main() {
  print(factorial(25));

  final digits = factorial(1000).toString();
  print('1000! has ${digits.length} digits');
  print('digit sum: ${digits.split('').map(int.parse).reduce((a, b) => a + b)}');

  print(fibonacci(100));
  print(fibonacci(93) > BigInt.from(9223372036854775807));

  final f = fibonacci(10000).toString();
  print('fib(10000): ${f.substring(0, 10)}...'
      '${f.substring(f.length - 10)} (${f.length} digits)');
}
15511210043330985984000000
1000! has 2568 digits
digit sum: 10539
354224848179261915075
true
fib(10000): 3364476487...9947366875 (2090 digits)

fibonacci(93) is the first Fibonacci number that doesn't fit in a 64-bit int. The Recursion article shows recursive versions of these functions.

Integer square root

BigInt has no sqrt(), and converting to double loses precision. Newton's method gives an exact integer square root:

/// Largest integer r such that r * r <= n.
BigInt isqrt(BigInt n) {
  if (n.isNegative) throw ArgumentError.value(n, 'n', 'must not be negative');
  if (n < BigInt.two) return n;
  var x = BigInt.one << ((n.bitLength + 1) >> 1); // initial guess >= sqrt(n)
  while (true) {
    final y = (x + n ~/ x) >> 1;
    if (y >= x) return x;
    x = y;
  }
}

void main() {
  print(isqrt(BigInt.from(99)));
  print(isqrt(BigInt.from(100)));

  // 50 decimal digits of sqrt(2): isqrt(2 * 10^100)
  final root = isqrt(BigInt.two * BigInt.from(10).pow(100)).toString();
  print('sqrt(2) = ${root[0]}.${root.substring(1)}');
}
9
10
sqrt(2) = 1.41421356237309504880168872420969807856967187537694

Scaling by a power of ten before taking the root, then placing the decimal point in the string, is a general trick for computing values to any precision with integers.

Modular arithmetic

Number theory and public-key cryptography work with huge numbers modulo some value. Computing base.pow(exp) % mod directly would create a gigantic intermediate number. modPow does it efficiently and keeps intermediate values small:

void main() {
  print(BigInt.from(4).modPow(BigInt.from(13), BigInt.from(497)));
  print(BigInt.from(4).pow(13) % BigInt.from(497));

  final big = BigInt.parse('123456789123456789');
  print(big.modPow(BigInt.parse('987654321987654321'), BigInt.from(1000000007)));

  print(BigInt.from(48).gcd(BigInt.from(180)));

  // 3 * 4 = 12 = 1 (mod 11), so 4 is the inverse of 3 modulo 11
  print(BigInt.from(3).modInverse(BigInt.from(11)));

  try {
    BigInt.from(4).modInverse(BigInt.from(8));
  } catch (e) {
    print(e);
  }
}
445
445
521382147
12
4
Exception: Not coprime

The third call would be impossible with pow(): the exponent has 18 digits. modInverse throws if the inverse doesn't exist, which happens when the numbers share a factor.

A probabilistic primality test

BigInt has no isPrime. The Miller-Rabin test is the standard way to check large numbers and needs only modPow:

import 'dart:math';

final _random = Random.secure();

/// A random BigInt in the range [0, max).
BigInt randomBelow(BigInt max) {
  final bytes = (max.bitLength + 7) >> 3;
  while (true) {
    var r = BigInt.zero;
    for (var i = 0; i < bytes; i++) {
      r = (r << 8) | BigInt.from(_random.nextInt(256));
    }
    r = r.toUnsigned(max.bitLength); // drop extra high bits
    if (r < max) return r;
  }
}

/// Miller-Rabin probabilistic primality test.
bool isProbablePrime(BigInt n, {int rounds = 20}) {
  if (n < BigInt.two) return false;
  for (final p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]) {
    final bp = BigInt.from(p);
    if (n == bp) return true;
    if (n % bp == BigInt.zero) return false;
  }
  // Write n - 1 as d * 2^s with d odd.
  final nMinus1 = n - BigInt.one;
  var d = nMinus1;
  var s = 0;
  while (d.isEven) {
    d >>= 1;
    s++;
  }
  outer:
  for (var i = 0; i < rounds; i++) {
    final a = randomBelow(n - BigInt.from(3)) + BigInt.two; // [2, n-2]
    var x = a.modPow(d, n);
    if (x == BigInt.one || x == nMinus1) continue;
    for (var r = 1; r < s; r++) {
      x = x.modPow(BigInt.two, n);
      if (x == nMinus1) continue outer;
    }
    return false;
  }
  return true;
}

BigInt nextProbablePrime(BigInt n) {
  var candidate = n.isEven ? n + BigInt.one : n + BigInt.two;
  while (!isProbablePrime(candidate)) {
    candidate += BigInt.two;
  }
  return candidate;
}

void main() {
  print(isProbablePrime(BigInt.from(97)));
  print(isProbablePrime(BigInt.from(561))); // Carmichael number, not prime
  final mersenne = BigInt.two.pow(127) - BigInt.one;
  print(isProbablePrime(mersenne));
  print(isProbablePrime(mersenne + BigInt.two));
  print(nextProbablePrime(BigInt.parse('1${'0' * 30}')));
  print(nextProbablePrime(BigInt.parse('6${'0' * 30}')));
}
true
false
true
false
1000000000000000000000000000057
6000000000000000000000000000109

With 20 rounds, the chance of a composite number passing is below 4^-20. randomBelow uses Random.secure() so the test can't be fooled by predictable witnesses; see Random numbers.

Toy RSA

With two primes, modInverse and modPow you have textbook RSA. The two primes found above make a 202-bit key:

import 'dart:convert';

// bytesToBigInt() and bigIntToBytes() from the "Converting to and from bytes" section

void main() {
  // Real keys use primes of 1024 bits or more.
  final p = BigInt.parse('1000000000000000000000000000057');
  final q = BigInt.parse('6000000000000000000000000000109');
  final n = p * q;
  final phi = (p - BigInt.one) * (q - BigInt.one);
  final e = BigInt.from(65537);
  final d = e.modInverse(phi);
  print('n = $n (${n.bitLength} bits)');
  print('d = $d');

  final message = bytesToBigInt(utf8.encode('Hi, Dart!'));
  print('message  = $message');
  final cipher = message.modPow(e, n);
  print('cipher   = $cipher');
  final decrypted = cipher.modPow(d, n);
  print('plain    = ${utf8.decode(bigIntToBytes(decrypted))}');
}
n = 6000000000000000000000000000451000000000000000000000000006213 (202 bits)
d = 777728611318797015426400354056056578726520896592764392633953
message  = 1335744041058110174241
cipher   = 2802065618405026936068654472689665786600742908909855075965822
plain    = Hi, Dart!

This is for learning only. Textbook RSA without padding is insecure, and BigInt operations are not constant-time. For real encryption and signatures use a vetted library, as described in Cryptography.

Exact decimals with scaled integers

double can't represent most decimal fractions exactly, which is a problem for money. A common fix is to store amounts as an integer number of the smallest unit (cents, or millionths). With BigInt there's also no upper limit:

/// A decimal number with a fixed number of fractional digits,
/// stored as a scaled BigInt: 12.34 with scale 2 is 1234.
class Fixed implements Comparable<Fixed> {
  static const scale = 6;
  static final _factor = BigInt.from(10).pow(scale);

  final BigInt units;
  const Fixed._(this.units);

  factory Fixed.parse(String s) {
    final negative = s.startsWith('-');
    if (negative) s = s.substring(1);
    final parts = s.split('.');
    final whole = parts[0];
    final frac = parts.length > 1 ? parts[1] : '';
    if (frac.length > scale) throw FormatException('too many digits', s);
    final units = BigInt.parse(whole + frac.padRight(scale, '0'));
    return Fixed._(negative ? -units : units);
  }

  Fixed operator +(Fixed other) => Fixed._(units + other.units);
  Fixed operator -(Fixed other) => Fixed._(units - other.units);

  /// Multiplies and rounds half away from zero.
  Fixed operator *(Fixed other) =>
      Fixed._(_divRound(units * other.units, _factor));

  Fixed operator /(Fixed other) =>
      Fixed._(_divRound(units * _factor, other.units));

  static BigInt _divRound(BigInt a, BigInt b) {
    final q = a ~/ b;
    final r = a.remainder(b);
    if (r.abs() * BigInt.two >= b.abs()) {
      return (a.isNegative != b.isNegative) ? q - BigInt.one : q + BigInt.one;
    }
    return q;
  }

  @override
  int compareTo(Fixed other) => units.compareTo(other.units);

  @override
  bool operator ==(Object other) => other is Fixed && other.units == units;

  @override
  int get hashCode => units.hashCode;

  @override
  String toString() {
    final digits = units.abs().toString().padLeft(scale + 1, '0');
    final cut = digits.length - scale;
    final sign = units.isNegative ? '-' : '';
    return '$sign${digits.substring(0, cut)}.${digits.substring(cut)}';
  }
}

void main() {
  print(0.1 + 0.2);
  print(Fixed.parse('0.1') + Fixed.parse('0.2'));

  final subtotal = Fixed.parse('19.99') * Fixed.parse('3');
  final tax = subtotal * Fixed.parse('0.0825');
  print('subtotal: $subtotal');
  print('tax:      $tax');
  print('total:    ${subtotal + tax}');

  print(Fixed.parse('1') / Fixed.parse('3'));
  print(Fixed.parse('-2') / Fixed.parse('3'));

  // Far beyond what a double can hold exactly.
  final balance = Fixed.parse('98765432109876543210.123456');
  print(balance + Fixed.parse('0.000001'));
  print(98765432109876543210.123456 + 0.000001);
}
0.30000000000000004
0.300000
subtotal: 59.970000
tax:      4.947525
total:    64.917525
0.333333
-0.666667
98765432109876543210.123457
98765432109876540000.0

The Fixed._ constructor is const, and the class overrides ==, hashCode and compareTo so values behave like numbers in collections. If you need variable precision or more rounding modes, the decimal package on pub.dev is built on BigInt in the same way.

BigInt and JSON

jsonEncode doesn't know about BigInt, and JSON numbers are decoded as int or double, so large values lose digits. Send them as strings:

import 'dart:convert';

class Account {
  final String name;
  final BigInt balance;
  Account(this.name, this.balance);

  Map<String, dynamic> toJson() =>
      {'name': name, 'balance': balance.toString()};

  factory Account.fromJson(Map<String, dynamic> json) =>
      Account(json['name'] as String, BigInt.parse(json['balance'] as String));
}

void main() {
  final value = BigInt.two.pow(80);
  try {
    jsonEncode({'value': value});
  } catch (e) {
    print(e);
  }

  final s = jsonEncode(Account('treasury', value));
  print(s);
  final back = Account.fromJson(jsonDecode(s) as Map<String, dynamic>);
  print(back.balance == value);

  // A fallback for any BigInt anywhere in the structure.
  print(jsonEncode({
    'ids': [BigInt.one << 70, 5]
  }, toEncodable: (o) => o is BigInt ? o.toString() : throw UnsupportedError('$o')));

  // A large number in JSON is decoded as a double.
  final decoded = jsonDecode('{"id": 12345678901234567890123}');
  print(decoded['id']);
  print(decoded['id'].runtimeType);
}
Converting object to an encodable object failed: Instance of '_BigIntImpl'
{"name":"treasury","balance":"1208925819614629174706176"}
true
{"ids":["1180591620717411303424",5]}
1.2345678901234568e+22
double

More on custom serialization in JSON.

Performance

BigInt values are heap-allocated objects and every operation creates a new one. Summing ten million numbers in a native executable (dart compile exe):

void main() {
  const n = 10000000;
  var sw = Stopwatch()..start();
  var s = 0;
  for (var i = 0; i < n; i++) {
    s += i;
  }
  print('int:    $s in ${sw.elapsedMilliseconds} ms');

  sw = Stopwatch()..start();
  var b = BigInt.zero;
  for (var i = 0; i < n; i++) {
    b += BigInt.from(i);
  }
  print('BigInt: $b in ${sw.elapsedMilliseconds} ms');
}
int:    49999995000000 in 3 ms
BigInt: 49999995000000 in 443 ms

That's more than 100 times slower, and the result would have fit in an int anyway. Use BigInt only where values can actually exceed 64 bits, and keep hot loops on int where possible. For example, accumulate in an int and switch to BigInt only when the value gets close to the limit.

BigInt on the web

When Dart is compiled to JavaScript, int is a JavaScript number. Integers above 2^53 lose precision without any error, but BigInt is still exact. The same program run on the VM and compiled with dart compile js and run in Node.js:

void main() {
  final max = 9007199254740991; // 2^53 - 1
  print(max + 2);
  print(BigInt.from(max) + BigInt.two);

  const id = '1234567890123456789';
  print(int.parse(id));
  print(BigInt.parse(id));
  print(BigInt.parse(id).isValidInt);
}

Dart VM:

9007199254740993
9007199254740993
1234567890123456789
1234567890123456789
true

JavaScript:

9007199254740992
9007199254740993
1234567890123456800
1234567890123456789
false

isValidInt respects the platform: on the web it returns false for anything that can't be represented exactly. If your code runs on both platforms and handles 64-bit IDs from a server, keep them as String or BigInt, never int. More platform differences are listed in Common pitfalls.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents