Search code examples
c++arrayshexuint8t

Hex_string to uint8_t msg[]


I want convert the characters in hex string

"0b7c28c9b7290c98d7438e70b3d3f7c848fbd7d1dc194ff83f4f7cc9b1378e98" 

to uint8_t msg[] and do not understand how to do it.

It seems simple, but have been unable to figure it out. I want to convert each character to a uint8_t hex value. For example if I have

string result = "0123456789abcdef";

How do I convert the string to:

uint8_t msg[] = "0123456789abcdef";

Solution

  • This func (thanks Converting a hex string to a byte array )

    vector<uint8_t> HexToBytes(const string& hex) {
      vector<uint8_t> bytes;
      for (unsigned int i = 0; i < hex.length(); i += 2) {
        string byteString = hex.substr(i, 2);
        uint8_t byte = (uint8_t) strtol(byteString.c_str(), nullptr, 16);
        bytes.push_back(byte);
      }
      return bytes;
    }
    

    using the above function we get the vector of bytes and call the method data()

    I want to thank the community now everything is working correctly. Thanks for the comments, I was already desperate that I could not do such a simple thing. Special thanks to @johnny-mopp