fork download
  1. #include <string>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <iostream>
  5. #include <iterator>
  6. #include <iomanip>
  7.  
  8. inline int char2hex(char c)
  9. {
  10. if (c >= '0' && c <= '9') return c - '0';
  11. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  12. if (c >= 'A' && c <= 'F') return c - 'A' + 10;
  13.  
  14. }
  15. std::vector<unsigned char> str2hex(const std::string& hexStr)
  16. {
  17. std::vector<unsigned char> retVal;
  18. bool highPart = ((hexStr.length() % 2) == 0);
  19. if (!highPart)
  20. retVal.push_back(0);
  21. std::for_each(hexStr.begin(), hexStr.end(),
  22. [&](char nextChar) {
  23. if (highPart)
  24. retVal.push_back(0x10 * char2hex(nextChar));
  25. else
  26. retVal.back() += char2hex(nextChar);
  27. highPart = !highPart;
  28. }
  29. );
  30.  
  31. return retVal;
  32. }
  33.  
  34. int main() {
  35. std::string someHex = "c45a1bf";
  36. std::vector<unsigned char> someUHex = str2hex(someHex);
  37. std::copy(someUHex.begin(), someUHex.end(), std::ostream_iterator<int>(std::cout << std::hex, ""));
  38. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
c45a1bf