Converting Strings to Hexadecimal and Vice Versa in C
Converting strings to hexadecimal and vice versa is a common task in many programming scenarios. In C , there are several approaches to accomplish this conversion efficiently.
String to Hexadecimal Conversion
To convert a string into its hexadecimal representation, we can utilize a loop and bitwise operations. For each character in the string, we can extract its ASCII value, convert it to hexadecimal using the bitshifting technique (right- and left-shifting), and append the resulting hex digits to an output string.
Here's an example implementation:
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; }
Hexadecimal to String Conversion
To decode a hexadecimal string back into its original character representation, we employ a similar loop structure. We parse the input string two characters at a time, convert each pair of hex digits into their corresponding ASCII value using a lookup table or bitwise operations, and accumulate the decoded characters in an output string.
Here's a function to perform this conversion:
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; } int hex_value(unsigned char hex_digit) { static const signed char hex_values[256] = {...}; int value = hex_values[hex_digit]; if (value == -1) throw std::invalid_argument("invalid hex digit"); return value; }
The above is the detailed content of How to Efficiently Convert Strings to Hexadecimal and Vice Versa in C ?. For more information, please follow other related articles on the PHP Chinese website!