![](/img/trans.png)
[英]How to convert a HexBytes Array to a String in C/C++ on Arduino?
[英]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] = '\0';
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]);
}
从字符串中一次获取两个字符(请参见例如std::string::substr
),然后使用std::stoi
转换为整数值。
首先,您使用的是不健康的C和C ++组合。 尝试选择一个并坚持下去(即使用其惯用法)。 您的代码有内存泄漏,不必要的副本等。
其次,您只需要两件事:
char
我想是一个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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.