Kav*_*han 0 c++ hex arduino decimal
我需要将十六进制字符串转换为十进制值。我使用了以下方法。但有时它返回错误的十进制值。
十六进制字符串的格式为“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;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
空格正在破坏转换。尝试这个:
#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 = %ld\n", test.c_str(), hexToDec(test));
return 0;
}
output:
'00 00 00 0c 1e' in dec = 3102
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3037 次 |
| 最近记录: |