将字符串转换为十六进制数组c++

convert string to hex array c++

本文关键字:数组 c++ 十六进制 字符串 转换      更新时间:2023-10-16

我有一个类似的字符串

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...

实时演示

在此处进行了解释C++将十六进制字符串转换为带符号整数

所以做这样的事情:

unsigned int x;  
std::string substring; // you will need to figure out how to get this
std::stringstream ss;
ss << std::hex << substring;
ss >> x;

x是存储数组所需的值。"48"实际上是字符串的解析部分。看这里,所以你可能需要更改类型。玩吧。我还认为你对字符串的解析不正确。检查这个使用循环将字符串拆分为特定长度的子单元