c++ 如何完成以下转换

string hexstr = "0011223300aabbccAABBCC00";
char chexstr[]= "0011223300aabbccAABBCC00";
const char* phexstr = "0011223300aabbccAABBCC00";

unsigned char hexchar[] = { 0x00,0x11,0x22,0x33,0x00,0xAA,0xBB,0xCC,0xAA,0xBB,0xCC,0x00 };

//怎么把上面未知长度的16进制字符串转换成unsigned char hexchar[]

这个有多个方法可以解:
方法一:
从C ++ 17开始,还有std :: from_chars。以下函数采用十六进制字符的字符串并返回T的向量:

#include <charconv>
template<typename T>
std::vector<T> hexstr_to_vec(const std::string& str, unsigned char chars_per_num = 2)
{
  std::vector<T> out(str.size() / chars_per_num, 0);

  T value;
  for (int i = 0; i < str.size() / chars_per_num; i++) {
    std::from_chars<T>(
      str.data() + (i * chars_per_num),
      str.data() + (i * chars_per_num) + chars_per_num,
      value,
      16
    );
    out[i] = value;
  }
  return out;
}

当然,给出的示例是使用的c++17的charconv
C++17提供了一组高性能,不抛出,不依赖本地环境的转换函数。在高吞吐量的环境下有良好的表现。
std::from_chars


```c++
#include <charconv>
struct from_chars_result {
    const char *ptr;
    std::errc ec;
};

enum class chars_format {
    scientific = /*unspecified*/,
    fixed = /*unspecified*/,
    hex = /*unspecified*/,
    general = fixed | scientific
};

std::from_chars_result from_chars(const char *frist,
    const char *last, /* integer */ &value, int base = 10);//c++17
std::from_chars_result from_chars(const char *frist,
    const char *last, /* floating */ &value,
    std::char_format fmt = std::chars_format::general); //c++17

或者,使用c代码也能解:
// 把十六进制字符串,转为字节码,每两个十六进制字符作为一个字节
unsigned char* HexToByte(const char* szHex)
{
    if (!szHex)
        return NULL;

    int iLen = strlen(szHex);

    if (iLen <= 0 || 0 != iLen % 2)
        return NULL;

    unsigned char* pbBuf = new unsigned char[iLen / 2];  // 数据缓冲区

    int tmp1, tmp2;
    for (int i = 0; i < iLen / 2; i++)
    {
        tmp1 = (int)szHex[i * 2] - (((int)szHex[i * 2] >= 'A') ? 'A' - 10 : '0');

        if (tmp1 >= 16)
            return NULL;

        tmp2 = (int)szHex[i * 2 + 1] - (((int)szHex[i * 2 + 1] >= 'A') ? 'A' - 10 : '0');

        if (tmp2 >= 16)
            return NULL;

        pbBuf[i] = (tmp1 * 16 + tmp2);
    }

    return pbBuf;
}

```

利用sscanf(%2x);,2位2位接收十六进制数,会自动转为10进制,直接存不就行了呗