#pragma once #include #include namespace odhtdb { class InvalidHexStringFormat : public std::runtime_error { public: InvalidHexStringFormat(const std::string &errMsg) : std::runtime_error(errMsg) {} }; // Returns -1 if c is not a hex string (0-9a-fA-F) static int __hexchar_to_num(int c) { if(c >= '0' && c <= '9') return c - '0'; else if(c >= 'a' && c <= 'f') return 10 + (c - 'a'); else if(c >= 'A' && c <= 'F') return 10 + (c - 'A'); else return -1; } // Throws InvalidHexStringFormat on invalid input static std::string hex2bin(const char *data, size_t dataSize) { if(dataSize % 2 != 0) throw InvalidHexStringFormat("Input string size is not of an even size"); std::string result; result.resize(dataSize / 2); for(int i = 0; i < dataSize; i += 2) { int v = __hexchar_to_num(data[i]); int v2 = __hexchar_to_num(data[i + 1]); if(v == -1) { std::string errMsg = "Invalid hex character: "; errMsg += data[i]; throw InvalidHexStringFormat(errMsg); } if(v2 == -1) { std::string errMsg = "Invalid hex character: "; errMsg += data[i + 1]; throw InvalidHexStringFormat(errMsg); } result[i / 2] = (v << 4) | v2; } return result; } }