1

I have a hex string in cpp

std::string str = "fe800000000000000cd86d653903694b";

I want to convert it to a char array which stores it like this

unsigned char ch[16] =     { 0xfe, 0x80, 0x00, 0x00,
                             0x00, 0x00, 0x00, 0x00,
                             0x0c, 0xd8, 0x6d, 0x65,
                             0x39, 0x03, 0x69, 0x4b };

I am thinking of traversing the string 2 characters at a time and storing it in a character array. But I was not able to find any library function that helps here.

for (size_t i = 0; i < str.length(); i += 2) 
{ 
      string part = hex.substr(i, 2); 
      //convert part to hex format and store it in ch
}

Any help is appreciated

Athul Sukumaran
  • 360
  • 4
  • 16

1 Answers1

1

I'm not an expert in C++ and for sure there is something better, but since nobody is answering ...

#include <iostream>

int main()
{
    std::string str = "fe800000000000000cd86d653903694b";
    unsigned char ch[16];

    for (size_t i = 0; i < str.length(); i += 2) 
    { 
        // Assign each pair converted to an integer
        ch[i / 2] = std::stoi(str.substr(i, 2), nullptr, 16);
    }
    for (size_t i = 0; i < sizeof ch; i++) 
    { 
        // Print each character as hex
        std::cout << std::hex << +ch[i];
    }
    std::cout << '\n';
}

and if you don't know the length of str beforehand:

#include <iostream>
#include <vector>

int main()
{
    std::string str = "fe800000000000000cd86d653903694b";
    std::vector<unsigned char> ch;

    for (size_t i = 0; i < str.length(); i += 2) 
    { 
        ch.push_back(std::stoi(str.substr(i, 2), nullptr, 16));
    }
    for (size_t i = 0; i < ch.size(); i++) 
    { 
        std::cout << std::hex << +ch[i];
    }
    std::cout << '\n';
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94