#include <cctype>
#include <iostream>
namespace {
int to_int(int c) {
if (not isxdigit(c)) return -1; // error: non-hexadecimal digit found
if (isdigit(c)) return c - '0';
if (isupper(c)) c = tolower(c);
return c - 'a' + 10;
}
template<class InputIterator, class OutputIterator> int
unhexlify(InputIterator first, InputIterator last, OutputIterator ascii) {
while (first != last) {
int top = to_int(*first++);
int bot = to_int(*first++);
if (top == -1 or bot == -1)
return -1; // error
*ascii++ = (top << 4) + bot;
}
return 0;
}
}
int main() {
char hex[] = "7B5a7D";
size_t len = sizeof(hex) - 1; // strlen
char ascii[len/2+1];
ascii[len/2] = '\0';
if (unhexlify(hex, hex+len, ascii) < 0) return 1; // error
std::cout << hex << " -> " << ascii << std::endl;
}
I2luY2x1ZGUgPGNjdHlwZT4KI2luY2x1ZGUgPGlvc3RyZWFtPgoKbmFtZXNwYWNlIHsKICBpbnQgdG9faW50KGludCBjKSB7CiAgICBpZiAobm90IGlzeGRpZ2l0KGMpKSByZXR1cm4gLTE7IC8vIGVycm9yOiBub24taGV4YWRlY2ltYWwgZGlnaXQgZm91bmQKICAgIGlmIChpc2RpZ2l0KGMpKSByZXR1cm4gYyAtICcwJzsKICAgIGlmIChpc3VwcGVyKGMpKSBjID0gdG9sb3dlcihjKTsKICAgIHJldHVybiBjIC0gJ2EnICsgMTA7CiAgfQoKICB0ZW1wbGF0ZTxjbGFzcyBJbnB1dEl0ZXJhdG9yLCBjbGFzcyBPdXRwdXRJdGVyYXRvcj4gaW50CiAgdW5oZXhsaWZ5KElucHV0SXRlcmF0b3IgZmlyc3QsIElucHV0SXRlcmF0b3IgbGFzdCwgT3V0cHV0SXRlcmF0b3IgYXNjaWkpIHsKICAgIHdoaWxlIChmaXJzdCAhPSBsYXN0KSB7CiAgICAgIGludCB0b3AgPSB0b19pbnQoKmZpcnN0KyspOwogICAgICBpbnQgYm90ID0gdG9faW50KCpmaXJzdCsrKTsKICAgICAgaWYgKHRvcCA9PSAtMSBvciBib3QgPT0gLTEpCglyZXR1cm4gL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