Converting Hexadecimal Strings to Strings in C
String conversion between hexadecimal and standard text formats requires a robust approach in C . Here's a detailed guide:
Convert String to Hexadecimal:
The string_to_hex() function offers a simple solution:
std::string string_to_hex(const std::string& input) { static const char hex_digits[] = "0123456789ABCDEF"; std::string output; output.reserve(input.length() * 2); for (unsigned char c : input) { output.push_back(hex_digits[c >> 4]); output.push_back(hex_digits[c & 15]); } return output; }
Convert Hexadecimal to String:
For converting from hexadecimal to string, the hex_to_string() function ensures accuracy:
std::string hex_to_string(const std::string& input) { const auto len = input.length(); if (len & 1) throw std::invalid_argument("odd length"); std::string output; output.reserve(len / 2); for (auto it = input.begin(); it != input.end(); ) { int hi = hex_value(*it++); int lo = hex_value(*it++); output.push_back(hi << 4 | lo); } return output; }
Example Usage:
To demonstrate the functionality:
std::string original_string = "Hello World"; std::string hex_string = string_to_hex(original_string); std::cout << "Hexadecimal representation: " << hex_string << std::endl; std::string recovered_string = hex_to_string(hex_string); std::cout << "Recovered string: " << recovered_string << std::endl;
Output:
Hexadecimal representation: 48656c6c6f20576f726c64 Recovered string: Hello World
The above is the detailed content of How to Efficiently Convert Between Hexadecimal Strings and Standard Strings in C ?. For more information, please follow other related articles on the PHP Chinese website!