base64ToBinary function

Uint8List base64ToBinary(
  1. String s
)

Convert an unsigned base-64 number in s to a bignum

Implementation

Uint8List base64ToBinary(String s) {
  var len = s.length;
  if ((len & 3) == 1 && s[len - 1] == '=') {
    len -= 1;
  } // fc appends an extra '='
  if ((len & 3) != 0) {
    throw 'base-64 value is not padded correctly';
  }
  var groups = len >> 2;
  var bytes = groups * 3;
  if (len > 0 && s[len - 1] == '=') {
    if (s[len - 2] == '=') {
      bytes -= 2;
    } else {
      bytes -= 1;
    }
  }
  var result = new Uint8List(bytes);

  for (var group = 0; group < groups; ++group) {
    var digit0 = base64Map[s.codeUnitAt(group * 4 + 0)];
    var digit1 = base64Map[s.codeUnitAt(group * 4 + 1)];
    var digit2 = base64Map[s.codeUnitAt(group * 4 + 2)];
    var digit3 = base64Map[s.codeUnitAt(group * 4 + 3)];
    result[group * 3 + 0] = (digit0 << 2) | (digit1 >> 4);
    if (group * 3 + 1 < bytes) {
      result[group * 3 + 1] = ((digit1 & 15) << 4) | (digit2 >> 2);
    }
    if (group * 3 + 2 < bytes) {
      result[group * 3 + 2] = ((digit2 & 3) << 6) | digit3;
    }
  }
  return result;
}