Converting a hex string to a byte array

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

    This can be done with a stringstream, you just need to store the value in an intermediate numeric type such as an int:

      std::string test = "01A1"; // assuming this is an even length string
      char bytes[test.length()/2];
      stringstream converter;
      for(int i = 0; i < test.length(); i+=2)
      {
          converter << std::hex << test.substr(i,2);
          int byte;
          converter >> byte;
          bytes[i/2] = byte & 0xFF;
          converter.str(std::string());
          converter.clear();
      }
    

提交回复
热议问题