如何将十六进制字符串拆分为std :: vector? [英] How to split a hex string into std::vector?
本文介绍了如何将十六进制字符串拆分为std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个十六进制 std :: string
像09e1c5f70a65ac519458e7e53f36
,我怎样才能将它分成两块数字并将它们存储到 std :: vector< uint8_t>
?
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;
}
推荐答案
#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;
}
这篇关于如何将十六进制字符串拆分为std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文