Converting a hex string to a byte array

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

    In: "303132", Out: "012". Input string can be odd or even length.

    char 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::runtime_error("Incorrect symbol in hex string");
    };
    
    string hex2str(string &hex)
    {
        string out;
        out.resize(hex.size() / 2 + hex.size() % 2);
    
        string::iterator it = hex.begin();
        string::iterator out_it = out.begin();
        if (hex.size() % 2 != 0) {
            *out_it++ = char(char2int(*it++));
        }
    
        for (; it < hex.end() - 1; it++) {
            *out_it++ = char2int(*it++) << 4 | char2int(*it);
        };
    
        return out;
    }
    

提交回复
热议问题