Converting a hex string to a byte array

后端 未结 19 1958
时光取名叫无心
时光取名叫无心 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 12:57

    This implementation uses the built-in strtol function to handle the actual conversion from text to bytes, but will work for any even-length hex string.

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

提交回复
热议问题