Base64.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. base64.cpp and base64.h
  3. Copyright (C) 2004-2008 René Nyffenegger
  4. This source code is provided 'as-is', without any express or implied
  5. warranty. In no event will the author be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this source code must not be misrepresented; you must not
  11. claim that you wrote the original source code. If you use this source code
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original source code.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. René Nyffenegger rene.nyffenegger@adp-gmbh.ch
  18. */
  19. /// Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  20. /// Originally by René Nyffenegger.
  21. /// DEVified by Gav Wood.
  22. #pragma once
  23. #include <string>
  24. #include "Common.h"
  25. #include "FixedHash.h"
  26. namespace dev
  27. {
  28. std::string toBase64(bytesConstRef _in);
  29. bytes fromBase64(std::string const& _in);
  30. template <size_t N> inline std::string toBase36(FixedHash<N> const& _h)
  31. {
  32. static char const* c_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  33. typename FixedHash<N>::Arith a = _h;
  34. std::string ret;
  35. for (; a > 0; a /= 36)
  36. {
  37. unsigned r = (unsigned)(a - a / 36 * 36); // boost's % is broken
  38. ret = c_alphabet[r] + ret;
  39. }
  40. return ret;
  41. }
  42. template <size_t N> inline FixedHash<N> fromBase36(std::string const& _h)
  43. {
  44. typename FixedHash<N>::Arith ret = 0;
  45. for (char c: _h)
  46. ret = ret * 36 + (c < 'A' ? c - '0' : (c - 'A' + 10));
  47. return ret;
  48. }
  49. }