Utils.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "Utils.h"
  2. #include "CommWrapperBase.h"
  3. #include <algorithm>
  4. #include <sstream>
  5. #include <iomanip>
  6. namespace Utils
  7. {
  8. // 字符串转字节数组
  9. std::vector<BYTE> ConvertHexStringToBytes(const std::string &hex_string)
  10. {
  11. std::string clean_hex = hex_string;
  12. // 移除空格
  13. clean_hex.erase(std::remove(clean_hex.begin(), clean_hex.end(), ' '), clean_hex.end());
  14. // 如果长度为奇数,补0
  15. if (clean_hex.length() % 2 != 0)
  16. {
  17. clean_hex += '0';
  18. }
  19. std::vector<BYTE> bytes;
  20. for (size_t i = 0; i < clean_hex.length(); i += 2)
  21. {
  22. std::string byte_str = clean_hex.substr(i, 2);
  23. BYTE byte_val = static_cast<BYTE>(std::stoul(byte_str, nullptr, 16));
  24. bytes.push_back(byte_val);
  25. }
  26. return bytes;
  27. }
  28. std::string Utils::ConvertBytesToHexString(const std::vector<BYTE> &bytes)
  29. {
  30. std::stringstream ss;
  31. for (size_t i = 0; i < bytes.size(); i++)
  32. {
  33. if (i > 0)
  34. ss << " ";
  35. ss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(bytes[i]);
  36. }
  37. return ss.str();
  38. }
  39. // 获取当前可执行文件目录
  40. std::string Utils::GetExecutableDirectory()
  41. {
  42. char buffer[MAX_PATH];
  43. GetModuleFileNameA(NULL, buffer, MAX_PATH);
  44. std::string::size_type pos = std::string(buffer).find_last_of("\\");
  45. return std::string(buffer).substr(0, pos);
  46. }
  47. } // namespace Utils