Arduino 十六进制到十进制转换

Arduino hex to decimal conversion

本文关键字:转换 十进制 十六进制 Arduino      更新时间:2023-10-16

我需要将十六进制字符串转换为十进制值。我使用了以下方法。但有时它会返回错误的十进制值。

十六进制字符串采用此格式"00 00 0C 6E">

unsigned long hexToDec(String hexString) {
unsigned long decValue = 0;
int nextInt;
for (long i = 0; i < hexString.length(); i++) {
nextInt = long(hexString.charAt(i));
if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
nextInt = constrain(nextInt, 0, 15);
decValue = (decValue * 16) + nextInt;
}
return decValue;
}

空格会污染转换。试试这个:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
unsigned long hexToDec(string hexString) {
unsigned long decValue = 0;
char nextInt;
for ( long i = 0; i < hexString.length(); i++ ) {
nextInt = toupper(hexString[i]);
if( isxdigit(nextInt) ) {
if (nextInt >= '0' && nextInt <= '9') nextInt = nextInt - '0';
if (nextInt >= 'A' && nextInt <= 'F') nextInt = nextInt - 'A' + 10;
decValue = (decValue << 4) + nextInt;
}
}
return decValue;
}
int main() {
string test = "00 00 00 0c 1e";
printf("'%s' in dec = %ldn", test.c_str(), hexToDec(test));
return 0;
}
output:
'00 00 00 0c 1e' in dec = 3102
为什么要
  1. 硬编码 ASCII 值?只需使用char文字 -'0''9''a''f'、...;它们的可读性更强。
  2. 不需要所有这些map,简单的数学运算就可以了;而且,不需要constrain,它只是隐藏了你的问题(见下一点(。
  3. 如果您遇到不在[0-9a-fA-F]范围内的字符而不是跳过它,您只是将其 ASCII 值限制为 0-15,这绝对不是您想要做的。

所以:

unsigned long hexToDec(String hexString) {
unsigned long ret;
for(int i=0, n=hexString.length(); i!=n; ++i) {
char ch = hexString[i];
int val = 0;
if('0'<=ch && ch<='9')      val = ch - '0';
else if('a'<=ch && ch<='f') val = ch - 'a' + 10;
else if('A'<=ch && ch<='F') val = ch - 'A' + 10;
else continue; // skip non-hex characters
ret = ret*16 + val;
}
return ret;
}

请注意,如果您获得的数据是某个整数的大转储,这将提供正确的结果。

十六进制字符串包含空格,但代码不会跳过它们,并且该函数constrain()有效地将空格转换为0xF,最终导致错误的结果。除此之外,您的代码还可以。

如果我要建议进行最少的更改,我会说:

nextInt = long(hexString.charAt(i));

将此添加到代码中:

if(isspace(nextInt))
continue;

请注意,isspace()函数是在ctype.h头文件中原型化的 C 标准库函数。

但是,如果我要对整个代码进行注释,那么您调用了太多函数,无法完成无需任何函数调用即可完成的工作。