base.hpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #pragma once
  2. //required bytes: ceil(bits / log2(base))
  3. //base57 => 128=22, 256=44, 512=88
  4. //base62 => 128=22, 256=43, 512=86
  5. //base64 => 128=22, 256=43, 512=86
  6. #include <nall/arithmetic.hpp>
  7. namespace nall::Encode {
  8. template<uint Bits, typename T> inline auto Base(T value) -> string {
  9. static const string format =
  10. Bits == 2 ? "01"
  11. : Bits == 8 ? "01234567"
  12. : Bits == 10 ? "0123456789"
  13. : Bits == 16 ? "0123456789abcdef"
  14. : Bits == 32 ? "0123456789abcdefghijklmnopqrstuv"
  15. : Bits == 34 ? "023456789abcdefghijkmnopqrstuvwxyz" //1l
  16. : Bits == 36 ? "0123456789abcdefghijklmnopqrstuvwxyz"
  17. : Bits == 57 ? "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" //01IOl
  18. : Bits == 62 ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  19. : Bits == 64 ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz{}"
  20. : Bits == 85 ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%()+,-.:;=@[]^_`{|}~" //\ "&'*/<>?
  21. : "";
  22. static const uint size = ceil(sizeof(T) * 8 / log2(Bits));
  23. string result;
  24. result.resize(size);
  25. char* data = result.get() + size;
  26. for(auto byte : result) {
  27. *--data = format[value % Bits];
  28. value /= Bits;
  29. }
  30. return result;
  31. }
  32. }