Arduino 十六进制到十进制转换
Arduino hex to decimal conversion
我需要将十六进制字符串转换为十进制值。我使用了以下方法。但有时它会返回错误的十进制值。
十六进制字符串采用此格式"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
为什么要
- 硬编码 ASCII 值?只需使用
char
文字 -'0'
、'9'
、'a'
、'f'
、...;它们的可读性更强。 - 不需要所有这些
map
,简单的数学运算就可以了;而且,不需要constrain
,它只是隐藏了你的问题(见下一点(。 - 如果您遇到不在
[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 标准库函数。
但是,如果我要对整个代码进行注释,那么您调用了太多函数,无法完成无需任何函数调用即可完成的工作。
相关文章:
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- C++从二进制转换为十进制数
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 将分数转换为十进制数并对其进行排序
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 十进制到二进制转换器 c++
- 如何在C ++中将二进制字符串128位转换为十进制字符串?
- 将二进制转换为十进制,我如何要求用户仅输入二进制
- 我正在尝试编写将 ASCII 转换为十进制、添加并转换回 ASCII 的软件
- 如何将QBytearrayBCD转换为十进制QString表示
- C++:二进制到十进制w/转换过程的外观
- 十六进制到十进制转换的未清理答案
- 如何在C++中将二进制编码十进制转换为 int
- 如何将带有浮点数的字符串转换为十进制?
- 如何使用链表将负十进制数转换为二进制?
- 将字符指针中的十六进制转换为十进制
- 使用 std::hex 将十六进制转换为十进制
- 十进制,包括负到 32 位二进制转换器
- 使用动态比特斯转换十进制数字