hex.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Minetest
  3. Copyright (C) 2013 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include <string>
  18. #include <string_view>
  19. static const char hex_chars[] = "0123456789abcdef";
  20. static inline std::string hex_encode(const char *data, unsigned int data_size)
  21. {
  22. std::string ret;
  23. ret.reserve(data_size * 2);
  24. char buf2[3];
  25. buf2[2] = '\0';
  26. for (unsigned int i = 0; i < data_size; i++) {
  27. unsigned char c = (unsigned char)data[i];
  28. buf2[0] = hex_chars[(c & 0xf0) >> 4];
  29. buf2[1] = hex_chars[c & 0x0f];
  30. ret.append(buf2);
  31. }
  32. return ret;
  33. }
  34. static inline std::string hex_encode(std::string_view data)
  35. {
  36. return hex_encode(data.data(), data.size());
  37. }
  38. static inline bool hex_digit_decode(char hexdigit, unsigned char &value)
  39. {
  40. if (hexdigit >= '0' && hexdigit <= '9')
  41. value = hexdigit - '0';
  42. else if (hexdigit >= 'A' && hexdigit <= 'F')
  43. value = hexdigit - 'A' + 10;
  44. else if (hexdigit >= 'a' && hexdigit <= 'f')
  45. value = hexdigit - 'a' + 10;
  46. else
  47. return false;
  48. return true;
  49. }