Open In App

How to Convert Hex String to Byte Array in C++?

A Hex String is a combination of the digits 0-9 and characters A-F and a byte array is an array used to store byte data types only. The default value of each element of the byte array is 0. In this article, we will learn how to convert a hex string to a byte array.

Example:



Input:
Hex String : "2f4a33"

Output: Byte Array : 47 74 51

Explanation: 
Hex String: "2f"
Therefore, "2f" is converted to 47.
(2*161) + (15*160) ) = 32 + 15 = 47
For "4a":
 (4 * 161  + 10 * 160) = 74
For "33":
(3 * 161 + 3 * 160) = 51
Therefore the output is: 47 74 51

Converting a Hex String to a Byte Array in C++

We can convert a hex string to a byte array in C++ by parsing the hex string and converting every pair of hexadecimal characters into their corresponding byte values.

Approach

C++ Program to Covert a Hex String to a Byte Array

The below program demonstrates how we can convert a hex string to a byte array in C++.






// C++ Program to illustrate how to covert a hex string to a
// byte array
#include <iostream>
#include <string>
#include <vector>
using namespace std;
  
// Function to convert a hex string to a byte array
vector<uint8_t>
hexStringToByteArray(const string& hexString)
{
    vector<uint8_t> byteArray;
  
    // Loop through the hex string, two characters at a time
    for (size_t i = 0; i < hexString.length(); i += 2) {
        // Extract two characters representing a byte
        string byteString = hexString.substr(i, 2);
  
        // Convert the byte string to a uint8_t value
        uint8_t byteValue = static_cast<uint8_t>(
            stoi(byteString, nullptr, 16));
  
        // Add the byte to the byte array
        byteArray.push_back(byteValue);
    }
  
    return byteArray;
}
  
int main()
{
    string hexString1 = "2f4a33";
    vector<uint8_t> byteArray1
        = hexStringToByteArray(hexString1);
  
    // Print the input and output
    cout << "Input Hex String: " << hexString1 << endl;
    cout << "Output Byte Array: ";
    for (uint8_t byte : byteArray1) {
        cout << static_cast<int>(byte) << " ";
    }
  
    return 0;
}

Output
Input Hex String: 2f4a33
Output Byte Array: 47 74 51 

Time Complexity: O(N), here N is the length of the hex string.
Auxilliary Space: O(N)


Article Tags :