base64_encode_atom.c 704 B

12345678910111213141516171819202122232425262728293031
  1. /*
  2. * Core routine to encode a single atomic base64 chunk.
  3. */
  4. #include "defs.h"
  5. #include "misc.h"
  6. void base64_encode_atom(const unsigned char *data, int n, char *out)
  7. {
  8. static const char base64_chars[] =
  9. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  10. unsigned word;
  11. word = data[0] << 16;
  12. if (n > 1)
  13. word |= data[1] << 8;
  14. if (n > 2)
  15. word |= data[2];
  16. out[0] = base64_chars[(word >> 18) & 0x3F];
  17. out[1] = base64_chars[(word >> 12) & 0x3F];
  18. if (n > 1)
  19. out[2] = base64_chars[(word >> 6) & 0x3F];
  20. else
  21. out[2] = '=';
  22. if (n > 2)
  23. out[3] = base64_chars[word & 0x3F];
  24. else
  25. out[3] = '=';
  26. }