将字符串转换为十六进制数组c++
convert string to hex array 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...
实时演示
在此处进行了解释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"实际上是字符串的解析部分。看这里,所以你可能需要更改类型。玩吧。我还认为你对字符串的解析不正确。检查这个使用循环将字符串拆分为特定长度的子单元
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '