bytesToBase64 method

String bytesToBase64 (List<int> bytes, [ bool urlSafe = false bool addLineSeparator = false ])

Implementation

static String bytesToBase64(List<int> bytes,
    [bool urlSafe = false, bool addLineSeparator = false]) {
  int len = bytes.length;
  if (len == 0) {
    return "";
  }
  final String lookup = urlSafe ? _encodeTableUrlSafe : _encodeTable;
  // Size of 24 bit chunks.
  final int remainderLength = len.remainder(3);
  final int chunkLength = len - remainderLength;
  // Size of base output.
  int outputLen = ((len ~/ 3) * 4) + ((remainderLength > 0) ? 4 : 0);
  // Add extra for line separators.
  if (addLineSeparator) {
    outputLen += ((outputLen - 1) ~/ LINE_LENGTH) << 1;
  }
  List<int> out = new List<int>(outputLen);

  // Encode 24 bit chunks.
  int j = 0, i = 0, c = 0;
  while (i < chunkLength) {
    int x = ((bytes[i++] << 16) & 0xFFFFFF) |
    ((bytes[i++] << 8) & 0xFFFFFF) |
    bytes[i++];
    out[j++] = lookup.codeUnitAt(x >> 18);
    out[j++] = lookup.codeUnitAt((x >> 12) & 0x3F);
    out[j++] = lookup.codeUnitAt((x >> 6) & 0x3F);
    out[j++] = lookup.codeUnitAt(x & 0x3f);
    // Add optional line separator for each 76 char output.
    if (addLineSeparator && ++c == 19 && j < outputLen - 2) {
      out[j++] = CR;
      out[j++] = LF;
      c = 0;
    }
  }

  // If input length if not a multiple of 3, encode remaining bytes and
  // add padding.
  if (remainderLength == 1) {
    int x = bytes[i];
    out[j++] = lookup.codeUnitAt(x >> 2);
    out[j++] = lookup.codeUnitAt((x << 4) & 0x3F);
    out[j++] = PAD;
    out[j++] = PAD;
  } else if (remainderLength == 2) {
    int x = bytes[i];
    int y = bytes[i + 1];
    out[j++] = lookup.codeUnitAt(x >> 2);
    out[j++] = lookup.codeUnitAt(((x << 4) | (y >> 4)) & 0x3F);
    out[j++] = lookup.codeUnitAt((y << 2) & 0x3F);
    out[j++] = PAD;
  }

  return new String.fromCharCodes(out);
}