Home > Backend Development > C++ > How to Convert a Hexadecimal String to a Byte Array in C ?

How to Convert a Hexadecimal String to a Byte Array in C ?

Susan Sarandon
Release: 2024-12-24 11:50:14
Original
538 people have browsed it

How to Convert a Hexadecimal String to a Byte Array in C  ?

Hexadecimal String to Byte Array Conversion

In programming scenarios, it is often necessary to convert hexadecimal strings, which represent binary data in a compact format, into byte arrays. Byte arrays are more suitable for direct data manipulation and storage.

One effective approach to this conversion involves utilizing the standard strtol() function. This function interprets a string of digits as a base-specified integer, allowing us to extract the integer representation of our hex characters.

Here's an implementation in C :

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 uses a loop to iteratively examine the hex string in pairs of characters. For each pair, it creates a substring representing a single hex byte and converts it to a char using strtol(), supplying a base of 16 for hexadecimal interpretation. The resulting char is then appended to the byte vector.

By utilizing this function, you can effortlessly convert hexadecimal strings into byte arrays, enabling efficient handling and storage of binary data.

The above is the detailed content of How to Convert a Hexadecimal 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