📅  最后修改于: 2023-12-03 15:39:15.588000             🧑  作者: Mango
在Arduino - C++中,有时需要将十六进制数值转换为十进制。这在处理I2C通讯和其他数字传感器时非常常见。以下是一些方法可以实现这个转换。
函数:
strtoul(const char* str, char **endptr, int base)
示例:
char hexValue[] = "1A";
long int decimalValue = strtol(hexValue, NULL, 16);
函数:
sscanf(const char* str, const char* format, ...)
示例:
char hexValue[] = "1A";
long int decimalValue;
sscanf(hexValue, "%x", &decimalValue);
示例:
char hexValue[] = "1A";
long int decimalValue = 0;
for (int i = 0; i < strlen(hexValue); i++) {
decimalValue = decimalValue << 4;
if (hexValue[i] >= '0' && hexValue[i] <= '9') {
decimalValue |= hexValue[i] - '0';
}
else if (hexValue[i] >= 'A' && hexValue[i] <= 'F') {
decimalValue |= hexValue[i] - 'A' + 10;
}
else if (hexValue[i] >= 'a' && hexValue[i] <= 'f') {
decimalValue |= hexValue[i] - 'a' + 10;
}
}
以上是三种常见的将十六进制数值转换为十进制数值的方法。选择哪种方法取决于个人喜好和代码风格。