encode function

String encode(
  1. Uint8List source, {
  2. String alphabet = bitcoin,
})

Encode Uint8List data into a string using the specified alphabet.

Implementation

String encode(Uint8List source, {String alphabet = bitcoin}) {
  if (source.isEmpty) {
    return "";
  }
  final length = alphabet.length;

  /// final characters = _loadAlphabet(alphabet);
  List<int> digits = [0];

  for (var i = 0; i < source.length; ++i) {
    var carry = source[i];
    for (var j = 0; j < digits.length; ++j) {
      carry += digits[j] << 8;
      digits[j] = carry % length;
      carry = carry ~/ length;
    }
    while (carry > 0) {
      digits.add(carry % length);
      carry = carry ~/ length;
    }
  }
  var string = "";

  /// Deal with leading zeros
  for (var k = 0; source[k] == 0 && k < source.length - 1; ++k) {
    string += alphabet[0];
  }

  /// Convert digits to a string
  for (var q = digits.length - 1; q >= 0; --q) {
    string += alphabet[digits[q]];
  }
  return string;
}