Converting a hex string to a byte array

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

    #include 
    #include 
    #include 
    
    int main() {
        std::string s("313233");
        char delim = ',';
        int len = s.size();
        for(int i = 2; i < len; i += 3, ++len) s.insert(i, 1, delim);
        std::istringstream is(s);
        std::ostringstream os;
        is >> std::hex;
        int n;
        while (is >> n) {
            char c = (char)n;
            os << std::string(&c, 1);
            if(is.peek() == delim) is.ignore();
        }
    
        // std::string form
        std::string byte_string = os.str();
        std::cout << byte_string << std::endl;
        printf("%s\n", byte_string.c_str());
    
        // std::vector form
        std::vector byte_vector(byte_string.begin(), byte_string.end());
        byte_vector.push_back('\0'); // needed for a c-string
        printf("%s\n", byte_vector.data());
    }
    

    The output is

    123
    123
    123
    

    '1' == 0x31, etc.

提交回复
热议问题