c++ - 在cpp中将十六进制字符串转换为字符数组
问题描述
我在 cpp 中有一个十六进制字符串
std::string str = "fe800000000000000cd86d653903694b";
我想将它转换为一个 char 数组,它像这样存储它
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';
}
推荐阅读
- json - JQ中的获取或默认函数?
- java - Angular 未通过 RESTful API 从 Spring 获取
- angular - 使用 formArray 时出现此错误:“ModalDialogComponent.html:6 ERROR TypeError: Cannot read property 'controls' of null”
- javascript - 我想开发一个 java 脚本代码,我使用空格键暂停 setInterval 函数
- node.js - 如何将令牌保存在本地存储(或 cookie)中?
- ruby-on-rails - 如果使用 Ruby on Rails 在 redis 中存在 eixists,我如何更新 HKEYS 字段
- google-cloud-platform - 即使在获得 HTTP 200/202/204 之后,google-cloud-pubsub 推送也会继续重试
- node.js - 如何在 Cpanel 中为 Node.js 应用程序配置端口?
- c++ - 使用基类构造函数定义子类构造函数
- java - Java 服务 SPI 和内存泄漏