c++将16进制char转化为10进制string
时间: 2024-12-17 09:51:12 浏览: 68
在C++中,将十六进制字符转换成十进制字符串,通常可以利用标准库函数`std::stringstream`或者直接通过循环遍历每一位十六进制数,然后将其转换为对应的整数值。这里是一个简单的示例:
```cpp
#include <sstream>
#include <iostream>
std::string hexToDecimal(const char* hexStr) {
std::stringstream ss;
int decimalValue = 0;
for (const auto& ch : hexStr) {
// 检查字符是否是有效的十六进制数字(A-F 或 a-f)
if ('0' <= ch && ch <= '9' || 'A' <= ch && ch <= 'F' || 'a' <= ch && ch <= 'f') {
decimalValue <<= 4; // 左移四位
if ('A' <= ch || 'a' <= ch)
decimalValue += ch - 'A' + 10; // A-F 和 a-f 转换成对应的10进制值
else
decimalValue += ch - '0'; // 0-9 直接转换
} else {
break; // 非法字符,结束转换
}
}
// 将整数值转换为字符串并返回
std::string result;
std::ostringstream oss;
oss << decimalValue;
return oss.str();
}
int main() {
const char hex[] = "FF"; // 示例十六进制字符串
std::cout << "Decimal value of " << hex << " is: " << hexToDecimal(hex) << std::endl;
return 0;
}
```
阅读全文
相关推荐


















