如果给出std::string
之类的"09e1c5f70a65ac519458e7e53f36"
,我怎样才能将它分成两位数的块并将它们存储到std::vector<uint8_t>
?
我按照块大小的步骤循环遍历字符串,但我不知道如何将十六进制块转换为数字。这是我到目前为止所做的。
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;
}
答案 0 :(得分:5)
这是一个班轮: - )
#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;
}
答案 1 :(得分:3)
#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 :(得分:-1)
两行就足够了,
char str[]="09e1c5f70a65ac519458e7e53f36";
std::vector<uint8_t> fifth (str, str+ sizeof(str) / sizeof(uint8_t) );