Converting a hex string to a byte array

后端 未结 19 1938
时光取名叫无心
时光取名叫无心 2020-11-22 12:10

What is the best way to convert a variable length hex string e.g. \"01A1\" to a byte array containing that data.

i.e converting this:

st         


        
相关标签:
19条回答
  • 2020-11-22 13:11

    This ought to work:

    int char2int(char input)
    {
      if(input >= '0' && input <= '9')
        return input - '0';
      if(input >= 'A' && input <= 'F')
        return input - 'A' + 10;
      if(input >= 'a' && input <= 'f')
        return input - 'a' + 10;
      throw std::invalid_argument("Invalid input string");
    }
    
    // This function assumes src to be a zero terminated sanitized string with
    // an even number of [0-9a-f] characters, and target to be sufficiently large
    void hex2bin(const char* src, char* target)
    {
      while(*src && src[1])
      {
        *(target++) = char2int(*src)*16 + char2int(src[1]);
        src += 2;
      }
    }
    

    Depending on your specific platform there's probably also a standard implementation though.

    0 讨论(0)
提交回复
热议问题