Hexadecimal String to Byte Array Conversion
In programming scenarios, it is often necessary to convert hexadecimal strings, which represent binary data in a compact format, into byte arrays. Byte arrays are more suitable for direct data manipulation and storage.
One effective approach to this conversion involves utilizing the standard strtol() function. This function interprets a string of digits as a base-specified integer, allowing us to extract the integer representation of our hex characters.
Here's an implementation in C :
std::vector<char> HexToBytes(const std::string& hex) { std::vector<char> bytes; for (unsigned int i = 0; i < hex.length(); i += 2) { std::string byteString = hex.substr(i, 2); char byte = (char) strtol(byteString.c_str(), NULL, 16); bytes.push_back(byte); } return bytes; }
This function uses a loop to iteratively examine the hex string in pairs of characters. For each pair, it creates a substring representing a single hex byte and converts it to a char using strtol(), supplying a base of 16 for hexadecimal interpretation. The resulting char is then appended to the byte vector.
By utilizing this function, you can effortlessly convert hexadecimal strings into byte arrays, enabling efficient handling and storage of binary data.
The above is the detailed content of How to Convert a Hexadecimal String to a Byte Array in C ?. For more information, please follow other related articles on the PHP Chinese website!