hex_util.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/hex_util.h"
  5. #include "common/logging/log.h"
  6. namespace Common {
  7. u8 ToHexNibble(char c1) {
  8. if (c1 >= 65 && c1 <= 70)
  9. return c1 - 55;
  10. if (c1 >= 97 && c1 <= 102)
  11. return c1 - 87;
  12. if (c1 >= 48 && c1 <= 57)
  13. return c1 - 48;
  14. LOG_ERROR(Common, "Invalid hex digit: 0x{:02X}", c1);
  15. return 0;
  16. }
  17. std::vector<u8> HexStringToVector(std::string_view str, bool little_endian) {
  18. std::vector<u8> out(str.size() / 2);
  19. if (little_endian) {
  20. for (std::size_t i = str.size() - 2; i <= str.size(); i -= 2)
  21. out[i / 2] = (ToHexNibble(str[i]) << 4) | ToHexNibble(str[i + 1]);
  22. } else {
  23. for (std::size_t i = 0; i < str.size(); i += 2)
  24. out[i / 2] = (ToHexNibble(str[i]) << 4) | ToHexNibble(str[i + 1]);
  25. }
  26. return out;
  27. }
  28. std::array<u8, 16> operator""_array16(const char* str, std::size_t len) {
  29. if (len != 32) {
  30. LOG_ERROR(Common,
  31. "Attempting to parse string to array that is not of correct size (expected=32, "
  32. "actual={}).",
  33. len);
  34. return {};
  35. }
  36. return HexStringToArray<16>(str);
  37. }
  38. std::array<u8, 32> operator""_array32(const char* str, std::size_t len) {
  39. if (len != 64) {
  40. LOG_ERROR(Common,
  41. "Attempting to parse string to array that is not of correct size (expected=64, "
  42. "actual={}).",
  43. len);
  44. return {};
  45. }
  46. return HexStringToArray<32>(str);
  47. }
  48. } // namespace Common