Home >Backend Development >C++ >How to Efficiently Convert a Hex String to a Byte Array in C ?
Hex String Conversion to Byte Array
Converting a variable length hex string to a byte array is a common task in programming, enabling the representation of binary data in a human-readable format. Here's how to achieve this efficiently:
To convert a hex string like "01A1" into a byte array, we can leverage the built-in strtol() function to perform the conversion. The following implementation creates a std::vector of characters to store the byte array:
std::vector<char> HexToBytes(const std::string& hex) { std::vector<char> bytes; // Loop through the hex string in pairs of characters for (unsigned int i = 0; i < hex.length(); i += 2) { // Extract the current pair of characters std::string byteString = hex.substr(i, 2); // Convert the pair to a char using strtol() char byte = (char)strtol(byteString.c_str(), NULL, 16); // Append the char to the byte array bytes.push_back(byte); } // Return the byte array return bytes; }
This approach works for any even-length hex string. The strtol() function takes a pointer to the character array byteString.c_str() and the base (16 for hexadecimal).
By using this HexToBytes() function, you can easily convert a hex string to a byte array, allowing you to work with binary data in a convenient and flexible manner.
The above is the detailed content of How to Efficiently Convert a Hex String to a Byte Array in C ?. For more information, please follow other related articles on the PHP Chinese website!