fork(3) download
  1. #include <cctype>
  2. #include <iostream>
  3.  
  4. namespace {
  5. int to_int(int c) {
  6. if (not isxdigit(c)) return -1; // error: non-hexadecimal digit found
  7. if (isdigit(c)) return c - '0';
  8. if (isupper(c)) c = tolower(c);
  9. return c - 'a' + 10;
  10. }
  11.  
  12. template<class InputIterator, class OutputIterator> int
  13. unhexlify(InputIterator first, InputIterator last, OutputIterator ascii) {
  14. while (first != last) {
  15. int top = to_int(*first++);
  16. int bot = to_int(*first++);
  17. if (top == -1 or bot == -1)
  18. return -1; // error
  19. *ascii++ = (top << 4) + bot;
  20. }
  21. return 0;
  22. }
  23. }
  24.  
  25. int main() {
  26. char hex[] = "7B5a7D";
  27. size_t len = sizeof(hex) - 1; // strlen
  28. char ascii[len/2+1];
  29. ascii[len/2] = '\0';
  30.  
  31. if (unhexlify(hex, hex+len, ascii) < 0) return 1; // error
  32. std::cout << hex << " -> " << ascii << std::endl;
  33. }
  34.  
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
7B5a7D -> {Z}