You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ScHex.cpp 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // Created by robin on 6/29/15.
  3. //
  4. #include <sstream>
  5. #include "ScHex.h"
  6. char ScHex::hexCharToInt(const char& c)
  7. {
  8. if (c >= 'a')
  9. return (char)(10 + (c - ('a' - 'A')) - 'A');
  10. if (c >= 'A')
  11. return (char)(10 + c - 'A');
  12. return c - '0';
  13. }
  14. ScByteArray ScHex::stringToByteArray(const std::string &str)
  15. {
  16. std::string hexa;
  17. for (auto c : str)
  18. {
  19. if (isxdigit(c))
  20. hexa += c;
  21. }
  22. if (hexa.size() % 2)
  23. hexa.insert(0, "0");
  24. auto data = new BYTE[hexa.size() / 2];
  25. for (size_t i = 0; i < hexa.size(); i += 2)
  26. {
  27. data[i / 2] = (hexCharToInt(hexa[i]) << 4) | hexCharToInt(hexa[i + 1]);
  28. }
  29. return ScByteArray(data, hexa.size() / 2);
  30. }
  31. std::string ScHex::byteArrayToString(const ScByteArray &bytes, const std::string &separator)
  32. {
  33. std::string res;
  34. for (DWORD i = 0; i < bytes.getSize();++i)
  35. {
  36. res += intToHexChar(bytes.getData()[i]);
  37. if (i != bytes.getSize() - 1)
  38. res += separator;
  39. }
  40. return res;
  41. }
  42. std::string ScHex::intToHexChar(const char &c)
  43. {
  44. std::string res;
  45. for (auto c1 : {(c & 0xf0) >> 4, c & 0x0f})
  46. {
  47. if (c1 < 10)
  48. res += '0' + c1;
  49. else
  50. res += 'A' + (c1 - 10);
  51. }
  52. return res;
  53. }