Home > Backend Development > C++ > How to Convert Hex Strings to Byte Arrays in C ?

How to Convert Hex Strings to Byte Arrays in C ?

Linda Hamilton
Release: 2024-12-19 11:03:33
Original
894 people have browsed it

How to Convert Hex Strings to Byte Arrays in C  ?

Converting Hex Strings to Byte Arrays

When working with binary data, it's often necessary to convert hexadecimal strings into byte arrays. The hex string represents the raw binary data in its hexadecimal format. Here's how you can accomplish this conversion in C using a variable-length hex string.

To convert the hex string "01A1" into a byte array, we'll use the following approach:

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;
}
Copy after login

This function iterates through the hex string, extracting pairs of characters at a time and converting them to their corresponding bytes using the strtol() function. The resulting byte array is then returned.

Once you have converted the hex string to a byte array, you can store it in a variable of type char* or std::vector as required by your specific application. By writing the byte array to a file and using the hexdump -C command, you can verify that the data corresponds to the original hex string.

The above is the detailed content of How to Convert Hex Strings to Byte Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template