void b64_decode()

in src/base64.c [66:99]


void b64_decode(const char* src, unsigned srclen, char* dst) {
  unsigned buf = 0;
  char c;
  int bits = 0;
  int pos = 0;
  int pad = 0;

  while (srclen--) {
    c = *src++;
    if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
    bits = 0;
    if (c != '=') {
      if (c > 0 && c < 127) bits = b64_to_bin[(int)c];
    } else {
      pad++;
    }
    buf = (buf << 6) | bits;
    pos++;
    if (pos == 4) {
      *dst++ = (buf >> 16) & 0xff;
      if (pad < 2) *dst++ = (buf >> 8) & 0xff;
      if (pad == 0) *dst++ = buf & 0xff;
      buf = 0;
      pos = 0;
    }
  }
  // no padding or partial padding. pos must be 2 or 3
  if (pos == 2) {
    *dst++ = (buf >> 4) & 0xff;
  } else if (pos == 3) {
    *dst++ = (buf >> 10) & 0xff;
    if (pad == 0) *dst++ = (buf >> 2) & 0xff;
  }
}