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

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