Converting a Hex String to a Byte Array
To convert a variable-length hex string like "01A1" into a byte array, there are several methods you can consider:
Using a Vector of Characters
The following code snippet demonstrates how to use a vector of characters to store the converted byte array:
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 takes a hex string as input and iterates through its characters in pairs. Each pair of characters is converted into a single byte using the strtol function, which interprets the hex string as a hexadecimal representation and returns the equivalent decimal value. The resulting byte is then appended to the vector.
Using a Character Array
Alternatively, you can store the byte array in a character array:
char* HexToBytes(const std::string& hex, int& length) { length = hex.length() / 2; char* bytes = new char[length]; for (unsigned int i = 0; i < hex.length(); i += 2) { std::string byteString = hex.substr(i, 2); bytes[i / 2] = (char) strtol(byteString.c_str(), NULL, 16); } return bytes; }
In this case, the function takes the hex string and an integer reference that will store the resulting length of the byte array. It dynamically allocates memory for the byte array and fills it in a similar manner as the vector-based solution.
Both these approaches produce a byte array that can be written to a file and correctly interpreted as the binary data represented by the original hex string.
The above is the detailed content of How Can I Convert a Hex String to a Byte Array in C ?. For more information, please follow other related articles on the PHP Chinese website!