简短版本:
我有一个字符串:0x4D;0x90;0x69
我想要一个数组
static const uint8_t array[] = {
0x4D, 0x90, 0x69
} 怎么做?
较长版本:
我有一个字符串(buffer),如下所示:那些十六进制“数字”之间的0x4D0x900x69是零宽度空间,我使用
std::vector<std::string> v{ explode(buffer, '\u200B') };我希望有一个包含uint8_t数据的向量。
我已经尝试过reinterpret_cast这个字符串了,这实际上起作用了。但是我把它放在一个the循环中,它应该将结果推入uint8_t向量,但是在向量中只有0x00。
std::vector < std::string > v {
explode(buffer, '\u200B')
};
std::vector < uint8_t * > ob;
for (auto n: v) {
uint8_t * p = reinterpret_cast < uint8_t * > ( & n);
//std::cout << n << " | " << p << std::endl;
ob.push_back(p);
};
for (auto na : ob) std::cout << na << std::endl;我在控制台只得到三个0x00。
我想要一个包含static const uint8_t arr[]的buffer分割。
编辑:我忘了在这里添加explode函数,它基本上只是一个拆分。`cpp
const std::vector<std::string> explode(const std::string& s, const char& c)
{
std::string buff{ "" };
std::vector<std::string> v;
for (auto n : s)
{
if (n != c) buff += n; else
if (n == c && buff != "") { v.push_back(buff); buff = ""; }
}
if (buff != "") v.push_back(buff);
return v;
}发布于 2019-06-12 11:26:18
for (auto n : v)这将获取v中每件事物的副本,该副本在循环体的持续时间内存在。
uint8_t * p = reinterpret_cast < uint8_t * > ( & n);这将为您提供一个指向重新解释后的本地复制事物的指针。
ob.push_back(p);这会将指针存储到向量中。
}这使得所有的指针都在晃动。
要修复这个UB,可以尝试使用for (const auto& n : v)。
然而,还有其他问题。每个“东西”都是一个std::string!将std::string*转换为uint8_t*是毫无意义的,并且不太清楚您的目的是什么。你是想把n.c_str()的结果投给uint8_t*吗?但这样做也没有真正取得任何成果。
我认为你需要调查一下 a sequence of characters as a number and convert it to an integer。
https://stackoverflow.com/questions/56560566
复制相似问题