如何在C++中将字符串转换为HexBytes数组
How to convert a String to a HexBytes Array in C++?
我在C++中找不到将字符串转换为十六进制字节数组的方法,我在C#中只有一个例子:
public static byte[] ToBytes(string input)
{
byte[] bytes = new byte[input.Length / 2];
for (int i = 0, j = 0; i < input.Length; j++, i += 2)
bytes[j] = byte.Parse(input.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
return bytes;
}
我试过这种方式
byteRead = "02000000ce1eb94f04b62e21dba62b396d885103396ed096fbb6c1680000000000000000223cc23c0df07a75eff6eabf22d6d5805105deff90f1617f27f58045352b31eb9d0160538c9d001900000000";
// BYTES HEX
char *hexstring = new char[byteRead.length()+1];
strcpy(hexstring,byteRead.c_str());
uint8_t str_len = strlen(hexstring);
for (i = 0; i < (str_len / 2); i++) {
sscanf(hexstring + 2*i, "%02x", &bytearray[i]);
}
更新
这里有一个解决方案,这项工作为我在Arduino Uno:
char hexstring[] = "020000009ecb752aac3e6d2101163b36f3e6bd67d0c95be402918f2f00000000000000001036e4ee6f31bc9a690053320286d84fbfe4e5ee0594b4ab72339366b3ff1734270061536c89001900000000";
int i;
int bytearray[80];
char tmp[3];
tmp[2] = ' ';
int j = 0;
for(i=0;i<strlen(hexstring);i+=2) {
tmp[0] = hexstring[i];
tmp[1] = hexstring[i+1];
bytearray[j] = strtol(tmp,0,16);
j+=1;
}
for(i=0;i<80;i+=1) {
Serial.println(bytearray[i]);
}
首先,您使用的是不健康的C和C++混合;试着选择其中一个并坚持下去(也就是说,使用它的习语(。你的代码有内存泄漏、不必要的副本等…
其次,你只需要两样东西:
- 一种将两个连续字符(十六进制数字(转换为数字对应字符的方法(我想是
char
?( - 存储连续转换的方法
首先,虽然确实可以使用sscanf
,但C++倾向于使用istream
,尽管这很棘手,因为没有"停止";所以我们可以手动完成:
char fromHexadecimal(char const digit) {
if ('0' <= digit and digit <= '9') { return digit - '0'; }
if ('a' <= digit and digit <= 'f') { return 10 + digit - 'a'; }
if ('A' <= digit and digit <= 'F') { return 10 + digit - 'A'; }
throw std::runtime_error("Unknown hexadecimal digit");
}
char fromHexadecimal(char digit0, char digit1) {
return fromHexadecimal(digit0) * 16 + fromHexadecimal(digit1);
}
有了这个障碍,我们就可以同时使用字符串进行输入和输出;毕竟,string
只是char
:的集合
std::string fromHexadecimal(std::string const& hex) {
if (hex.size() % 2 != 0) {
throw std::runtime_error("Requires an even number of hex digits");
}
std::string result;
for (size_t i = 0, max = hex.size() / 2; i != max; ++i) {
result.push_back(fromHexadecimal(hex.at(2*i), hex.at(2*i+1)));
}
return result;
}
一次从字符串中获取两个字符(例如参见std::string::substr
(,并使用std::stoi
转换为整数值。
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 如何在C++中将字符串转换为HexBytes数组