hex_util.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. #pragma once
  5. #include <array>
  6. #include <cstddef>
  7. #include <string>
  8. #include <type_traits>
  9. #include <vector>
  10. #include <fmt/format.h>
  11. #include "common/common_types.h"
  12. namespace Common {
  13. [[nodiscard]] constexpr u8 ToHexNibble(char c) {
  14. if (c >= 65 && c <= 70) {
  15. return static_cast<u8>(c - 55);
  16. }
  17. if (c >= 97 && c <= 102) {
  18. return static_cast<u8>(c - 87);
  19. }
  20. return static_cast<u8>(c - 48);
  21. }
  22. [[nodiscard]] std::vector<u8> HexStringToVector(std::string_view str, bool little_endian);
  23. template <std::size_t Size, bool le = false>
  24. [[nodiscard]] constexpr std::array<u8, Size> HexStringToArray(std::string_view str) {
  25. std::array<u8, Size> out{};
  26. if constexpr (le) {
  27. for (std::size_t i = 2 * Size - 2; i <= 2 * Size; i -= 2) {
  28. out[i / 2] = static_cast<u8>((ToHexNibble(str[i]) << 4) | ToHexNibble(str[i + 1]));
  29. }
  30. } else {
  31. for (std::size_t i = 0; i < 2 * Size; i += 2) {
  32. out[i / 2] = static_cast<u8>((ToHexNibble(str[i]) << 4) | ToHexNibble(str[i + 1]));
  33. }
  34. }
  35. return out;
  36. }
  37. template <typename ContiguousContainer>
  38. [[nodiscard]] std::string HexToString(const ContiguousContainer& data, bool upper = true) {
  39. static_assert(std::is_same_v<typename ContiguousContainer::value_type, u8>,
  40. "Underlying type within the contiguous container must be u8.");
  41. constexpr std::size_t pad_width = 2;
  42. std::string out;
  43. out.reserve(std::size(data) * pad_width);
  44. for (const u8 c : data) {
  45. out += fmt::format(upper ? "{:02X}" : "{:02x}", c);
  46. }
  47. return out;
  48. }
  49. [[nodiscard]] constexpr std::array<u8, 16> AsArray(const char (&data)[17]) {
  50. return HexStringToArray<16>(data);
  51. }
  52. [[nodiscard]] constexpr std::array<u8, 32> AsArray(const char (&data)[65]) {
  53. return HexStringToArray<32>(data);
  54. }
  55. } // namespace Common