hex_util.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/assert.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. ASSERT_MSG(Size * 2 <= str.size(), "Invalid string size");
  26. std::array<u8, Size> out{};
  27. if constexpr (le) {
  28. for (std::size_t i = 2 * Size - 2; i <= 2 * Size; i -= 2) {
  29. out[i / 2] = static_cast<u8>((ToHexNibble(str[i]) << 4) | ToHexNibble(str[i + 1]));
  30. }
  31. } else {
  32. for (std::size_t i = 0; i < 2 * Size; i += 2) {
  33. out[i / 2] = static_cast<u8>((ToHexNibble(str[i]) << 4) | ToHexNibble(str[i + 1]));
  34. }
  35. }
  36. return out;
  37. }
  38. template <typename ContiguousContainer>
  39. [[nodiscard]] std::string HexToString(const ContiguousContainer& data, bool upper = true) {
  40. static_assert(std::is_same_v<typename ContiguousContainer::value_type, u8>,
  41. "Underlying type within the contiguous container must be u8.");
  42. constexpr std::size_t pad_width = 2;
  43. std::string out;
  44. out.reserve(std::size(data) * pad_width);
  45. const auto format_str = fmt::runtime(upper ? "{:02X}" : "{:02x}");
  46. for (const u8 c : data) {
  47. out += fmt::format(format_str, c);
  48. }
  49. return out;
  50. }
  51. [[nodiscard]] constexpr std::array<u8, 16> AsArray(const char (&data)[33]) {
  52. return HexStringToArray<16>(data);
  53. }
  54. [[nodiscard]] constexpr std::array<u8, 32> AsArray(const char (&data)[65]) {
  55. return HexStringToArray<32>(data);
  56. }
  57. } // namespace Common