0

What is a simple way to write a function that coverts a c++ std::string which is in hexadecimal format into a uint8_t array?

For example:

#include <cstdint.h> //for uint8_t
#include <cstring.h> //for size_t


uint8_t output[64];
std::string input("EC83515650243FC512269A59CE0A82F4D4C92CD09F6037026BAA1A56AA97EBCB");
int ret = 0;


ret = hexStrToByteArray(input, output, sizeof(output));

Bonus points if you use C++17.

I think the function hexStrToByteArray can be something like:

int hexStrToByteArray(std::string input, uint8_t * output, size_t outLen)
{
  if(input.length()/2 != outLen)
  {
    return -1;
  }

  //TODO convert input into output
}

This seems like it should have already been answered on stack overflow, but I could only find answers that did the conversation in a c-like style or where the output was a vector instead of an array.

boochbrain
  • 69
  • 5
  • What are these bonus points you're referring to? Is there more for using c++20? – cigien Aug 08 '20 at 18:49
  • *or where the output was a vector instead of an array* -- Please link to these answers, since whatever they did with a vector, you could probably do the same thing with an array. – PaulMcKenzie Aug 08 '20 at 18:59
  • _"find answers that did the conversation in a c-like style"_, but C++ is a superset of C? Solutions in C works in C++. What's the problem of the answers that you found in C? – Ted Klein Bergman Aug 08 '20 at 19:18
  • 1
    Is this so hard that you couldn't even attempt a solution yourself? Practise solving problems like this is what will improve you as a programmer. Asking for the code from SO will not. If you have had a go and got stuck then please post the code here and someone will help you fix it. – john Aug 08 '20 at 19:42
  • You need to show some examples of input output, and at least *some* effort at solving it yourself. – cigien Aug 08 '20 at 21:22
  • Figure it out yourself, you'll be happier you did. Here's the answer key: https://stackoverflow.com/questions/17261798/converting-a-hex-string-to-a-byte-array (there are both C and C++ solutions.) – Andy Aug 08 '20 at 23:10

0 Answers0