将十六进制字符串转换为cpp中的字符数组



我在cpp 中有一个十六进制字符串

std::string str = "fe800000000000000cd86d653903694b";

我想把它转换成一个字符数组,像这个一样存储它

unsigned char ch[16] =     { 0xfe, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x0c, 0xd8, 0x6d, 0x65,
0x39, 0x03, 0x69, 0x4b };

我正在考虑一次遍历字符串2个字符,并将其存储在一个字符数组中。但是我在这里找不到任何有帮助的库函数。

for (size_t i = 0; i < str.length(); i += 2) 
{ 
string part = hex.substr(i, 2); 
//convert part to hex format and store it in ch
}

感谢提供的任何帮助

我不是C++专家,当然还有更好的东西,但由于没有人回答。。。

#include <iostream>
int main()
{
std::string str = "fe800000000000000cd86d653903694b";
unsigned char ch[16];
for (size_t i = 0; i < str.length(); i += 2) 
{ 
// Assign each pair converted to an integer
ch[i / 2] = std::stoi(str.substr(i, 2), nullptr, 16);
}
for (size_t i = 0; i < sizeof ch; i++) 
{ 
// Print each character as hex
std::cout << std::hex << +ch[i];
}
std::cout << 'n';
}

如果你事先不知道str的长度:

#include <iostream>
#include <vector>
int main()
{
std::string str = "fe800000000000000cd86d653903694b";
std::vector<unsigned char> ch;
for (size_t i = 0; i < str.length(); i += 2) 
{ 
ch.push_back(std::stoi(str.substr(i, 2), nullptr, 16));
}
for (size_t i = 0; i < ch.size(); i++) 
{ 
std::cout << std::hex << +ch[i];
}
std::cout << 'n';
}

最新更新