c++ hex string to byte conversion -


i have method gets string of consecutive bytes , need array of bytes out of it:

void  getbytearray(string paddedresistance) {    unsigned char cmd[4]={0x00,0x00,0x00,0x00};      list<string> resistancebytesasstring;      (int = 0; < paddedresistance.size(); i+=2)    {        resistancebytesasstring.push_back(paddedresistance.substr(i, 2));     } } 

this input value : "00000100"

and split , add list 4 separate strings:

00 00 01 00

i need convert each of them in order able populate cmd unsigned char array can't figure out how it.

in c# use

convert.tobyte(mystring, 16); 

to populate byte array.

consider using this:

std::vector<std::string> resistancebytesasstring{"00","01","10","11"};  std::vector<unsigned char> bytes(resistancebytesasstring.size()); std::transform(     resistancebytesasstring.begin(),      resistancebytesasstring.end(),     bytes.begin(),     [](const std::string& str) {         // convert string of length 2 byte.         // use stringstream hex option.         unsigned char byte = (str[0] - '0') << 1 | (str[1] - '0');         return byte; }); 

live working example


Comments