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

How to Convert a Hex String to a Byte Array or Character Array in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 05:27:10247browse

How to Convert a Hex String to a Byte Array or Character Array in C  ?

Converting a Hex String to a Byte Array

In the realm of data handling, it often becomes necessary to convert hex strings into byte arrays to facilitate efficient storage and processing. This process involves translating each pair of hexadecimal digits into their corresponding binary representation.

Converting Hex String to Character Array

If you wish to convert a hex string into a character array, you can leverage the following code:

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 implementation capitalizes on the intrinsic strtol() function that proficiently transforms text into bytes. Notably, it's capable of handling any even-length hex string.

Example:

std::string hex = "01A1";
auto bytes = HexToBytes(hex);

This code converts the hex string "01A1" into a character array named bytes containing the binary data. Subsequently, you can write this data to a file and examine it using hexdump -C to validate its accuracy.

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

Statement:
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