Home > Backend Development > C++ > How Can I Convert a Hex String to a Byte Array in C ?

How Can I Convert a Hex String to a Byte Array in C ?

Patricia Arquette
Release: 2025-01-01 01:22:16
Original
643 people have browsed it

How Can I Convert a Hex String to a Byte Array in C  ?

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

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

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!

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