How to split a hex string into std::vector?

一曲冷凌霜 提交于 2019-12-11 10:08:50

问题


Given a hex std::string like "09e1c5f70a65ac519458e7e53f36", how can I split it in chunks of two digits and store them into an std::vector<uint8_t>?

I loop over the string in steps of the chunk size, but I don't know how to convert the hex chunk into a number. This is what I have so far.

vector<byte> vectorify(string input, int chunk = 2)
{
    vector<uint8_t> result;
    for(size_t i = 0; i < input.length(); i += chunk)
    {
        int hex = input.substr(i, chunk);
        // ...
    }
    return result;
}

回答1:


#include <string>
#include <sstream>
#include <vector>
#include <iomanip>

int main(void)
{
    std::string in("09e1c5f70a65ac519458e7e53f36");
    size_t len = in.length();
    std::vector<uint8_t> out;
    for(size_t i = 0; i < len; i += 2) {
        std::istringstream strm(in.substr(i, 2));
        uint8_t x;
        strm >> std::hex >> x;
        out.push_back(x);
    }
    // "out" contains the solution
    return 0;
}



回答2:


It's a one liner :-)

#include <string>
#include <vector>
#include <boost/algorithm/hex.hpp>

int main(int argc, const char * argv[]) {
    std::string in("09e1c5f70a65ac519458e7e53f36");
    std::vector<uint8_t> out;
    boost::algorithm::unhex(in.begin(), in.end(), std::back_inserter(out));
    return 0;
    }



回答3:


two lines are enough,

    char str[]="09e1c5f70a65ac519458e7e53f36";
    std::vector<uint8_t> fifth (str, str+ sizeof(str) / sizeof(uint8_t) );


来源:https://stackoverflow.com/questions/21365364/how-to-split-a-hex-string-into-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!