base64.hpp 1009 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #pragma once
  2. namespace nall::Decode {
  3. inline auto Base64(const string& text) -> vector<uint8_t> {
  4. static bool initialized = false;
  5. static uint8_t lookup[256] = {0};
  6. if(!initialized) {
  7. initialized = true;
  8. for(uint n : range(26)) lookup['A' + n] = n;
  9. for(uint n : range(26)) lookup['a' + n] = n + 26;
  10. for(uint n : range(10)) lookup['0' + n] = n + 52;
  11. lookup['+'] = lookup['-'] = 62;
  12. lookup['/'] = lookup['_'] = 63;
  13. }
  14. vector<uint8_t> result;
  15. uint8_t buffer, output;
  16. for(uint n : range(text.size())) {
  17. uint8_t buffer = lookup[text[n]];
  18. switch(n & 3) {
  19. case 0:
  20. output = buffer << 2;
  21. break;
  22. case 1:
  23. result.append(output | buffer >> 4);
  24. output = (buffer & 15) << 4;
  25. break;
  26. case 2:
  27. result.append(output | buffer >> 2);
  28. output = (buffer & 3) << 6;
  29. break;
  30. case 3:
  31. result.append(output | buffer);
  32. break;
  33. }
  34. }
  35. if(text.size() & 3) result.append(output | buffer);
  36. return result;
  37. }
  38. }