How to convert a hex to a byte array in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <vector>
 
std::vector<char> HexToByteArray(const std::string& hex) {
    std::vector<char> bytes;
    int len = hex.length();
 
    for (unsigned int i = 0; i < len; i += 2) {
        std::string byteString = hex.substr(i, 2);
        char byte = (char) strtol(byteString.c_str(), NULL, 16);
        bytes.push_back(byte);
    }
 
    return bytes;
}
 
int main() {
    std::string str = "1A2D3E4F";
 
    std::vector<char> byteArray = HexToByteArray(str);
 
    for (int byte : byteArray) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << std::uppercase << byte << " ";
    }
}
 
 
 
/*
run:
 
1A 2D 3E 4F 
 
*/

 



answered Feb 14, 2025 by avibootz
edited Feb 14, 2025 by avibootz

Related questions

2 answers 246 views
1 answer 218 views
2 answers 238 views
238 views asked Feb 14, 2025 by avibootz
1 answer 187 views
...