base64_to.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <stddef.h>
  2. #include <stdint.h>
  3. #include "types.h"
  4. #include "base64.h"
  5. static const char base64t[64] = {
  6. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  7. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  8. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  9. 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  10. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  11. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  12. 'w', 'x', 'y', 'z', '0', '1', '2', '3',
  13. '4', '5', '6', '7', '8', '9', '+', '/',
  14. };
  15. char *base64_to(char *dst,const u8 *src,size_t slen)
  16. {
  17. if (!slen) {
  18. *dst = '\0';
  19. return dst;
  20. }
  21. for(size_t i = 0; i < slen;) {
  22. u32 threebytes = 0;
  23. threebytes |= (i < slen ? (unsigned char)src[i++] : (unsigned char)0) << (2 * 8);
  24. threebytes |= (i < slen ? (unsigned char)src[i++] : (unsigned char)0) << (1 * 8);
  25. threebytes |= (i < slen ? (unsigned char)src[i++] : (unsigned char)0) << (0 * 8);
  26. *dst++ = base64t[(threebytes >> (3 * 6)) & 63];
  27. *dst++ = base64t[(threebytes >> (2 * 6)) & 63];
  28. *dst++ = base64t[(threebytes >> (1 * 6)) & 63];
  29. *dst++ = base64t[(threebytes >> (0 * 6)) & 63];
  30. }
  31. switch (slen % 3) {
  32. case 0 : break;
  33. case 1 : {
  34. *(dst-2) = '=';
  35. *(dst-1) = '=';
  36. break;
  37. }
  38. case 2 : {
  39. *(dst-1) = '=';
  40. break;
  41. }
  42. }
  43. *dst = '\0';
  44. return dst;
  45. }