c++ - 将字符串转换为十六进制数组 C++
问题描述
我有一个字符串
string test = "48656c6c6f20576f726c64";
我想把它转换成
unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
unsigned char bytearray[60];
int w;
for (w=0;w<str.length();w+2) {
bytearray[w] = "0x" + str2[w];
}
它似乎不起作用。任何帮助,将不胜感激
解决方案
尝试更多类似的东西:
#include <vector>
#include <string>
std::string test = "48656c6c6f20576f726c64";
size_t numbytes = test.size() / 2;
std::vector<unsigned char> bytearray;
bytearray.reserve(numbytes);
for (size_t w = 0, x = 0; w < numbytes; ++w, x += 2) {
unsigned char b;
char c = test[x];
if ((c >= '0') && (c <= '9'))
b = (c - '0');
else if ((c >= 'A') && (c <= 'F'))
b = 10 + (c - 'A');
else if ((c >= 'a') && (c <= 'f'))
b = 10 + (c - 'a');
else {
// error!
break;
}
b <<= 4;
c = test[x+1];
if ((c >= '0') && (c <= '9'))
b |= (c - '0');
else if ((c >= 'A') && (c <= 'F'))
b |= 10 + (c - 'A');
else if ((c >= 'a') && (c <= 'f'))
b |= 10 + (c - 'a');
else {
// error!
break;
}
bytearray.push_back(b);
}
// use bytearray as needed...
或者:
#include <vector>
#include <string>
#include <iomanip>
std::string test = "48656c6c6f20576f726c64";
size_t numbytes = test.size() / 2;
std::vector<unsigned char> bytearray;
bytearray.reserve(numbytes);
for(size_t w = 0, x = 0; w < numbytes; ++w, x += 2)
{
std::istringstream iss(test.substr(x, 2));
unsigned short b;
if (!(iss >> std::hex >> b)) {
// error!
break;
}
bytearray.push_back(static_cast<unsigned char>(b));
}
// use bytearray as needed...
推荐阅读
- android - 使用 NavController 时,如何将数据从目标 Fragment 的 FloatingActionButton 的 OnClickListener 传递到起始 Fragment?
- c++ - C++ 返回值存储在堆栈帧中
- laravel - Laravel 多态多对多与 Pivot - 同步
- python - 遍历数据框中的列并在同一张图上绘图(Python)
- reactjs - 如何解决 react create app 'sh' 不是有效命令?
- reactjs - 如何使用 useState 挂钩更新对象状态
- python - Flask-login 在带有 @login_required 的页面上引发 401 状态
- rx-java2 - 如何使用 SSE(服务器发送事件)处理 RxJava2 Flowable 上的浏览器关闭情况(动作/事件)
- terraform - Terraform - 从地图创建更多虚拟机
- magento2 - 自定义产品属性未显示在管理中 (Magento 2.4.0)