hex_util.h 2.0 KB

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