微信小程序营销推广win10系统优化工具
在C++中进行进制转换可以通过标准库函数或自定义算法实现。以下是两种常见场景的转换方法及示例代码:
一、使用C++标准库函数
- 任意进制转十进制
#include <string>
#include <iostream>int main() {std::string num = "1A3F"; // 十六进制数int decimal = stoi(num, nullptr, 16); // 第三个参数指定原始进制std::cout << decimal; // 输出:6719
}
- 十进制转其他进制
#include <bitset>
#include <iostream>int main() {int num = 255;// 转二进制(8位)std::cout << std::bitset<8>(num) << "\n"; // 11111111// 转十六进制(小写)std::cout << std::hex << num << "\n"; // ff// 转八进制std::cout << std::oct << num; // 377
}
二、自定义转换函数(支持任意2-36进制)
1. 十进制转任意进制
#include <algorithm>
#include <string>std::string dec_to_base(int num, int base) {if (base < 2 || base > 36) return "";std::string result;const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";while (num > 0) {result += digits[num % base];num /= base;}if (result.empty()) return "0";std::reverse(result.begin(), result.end());return result;
}// 示例:dec_to_base(255, 16) 返回 "FF"
2. 任意进制转十进制
#include <cctype>
#include <string>int base_to_dec(std::string num, int base) {if (base < 2 || base > 36) return -1;int result = 0;for (char c : num) {int value = isdigit(c) ? c - '0' : toupper(c) - 'A' + 10;if (value >= base) return -1; // 非法输入result = result * base + value;}return result;
}// 示例:base_to_dec("FF", 16) 返回 255
三、完整示例代码
#include <iostream>
#include <algorithm>
#include <string>using namespace std;// 十进制转任意进制(2-36)
string dec_to_base(int num, int base) {if (base < 2 || base > 36) return "Invalid base";string result;const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";do {result += digits[num % base];num /= base;} while (num > 0);reverse(result.begin(), result.end());return result.empty() ? "0" : result;
}// 任意进制转十进制(2-36)
int base_to_dec(string num, int base) {if (base < 2 || base > 36) return -1;int result = 0;for (char c : num) {int value = isdigit(c) ? c - '0' : toupper(c) - 'A' + 10;if (value >= base) return -1;result = result * base + value;}return result;
}int main() {// 十进制255转十六进制cout << dec_to_base(255, 16) << endl; // 输出FF// 二进制11111111转十进制cout << base_to_dec("11111111", 2) << endl; // 输出255// 三十六进制转换示例cout << dec_to_base(1234, 36) << endl; // 输出YAcout << base_to_dec("YA", 36) << endl; // 输出1234return 0;
}
四、注意事项
- 有效性检查:需验证输入数值是否合法(如二进制不能包含2-9)
- 大小写处理:自定义函数默认处理大写字母,可修改
toupper()
为tolower()
处理小写 - 负数处理:示例代码未处理负数,需要时可添加符号处理
- 大数支持:对于超过
int
范围的数值,建议使用字符串处理或long long
类型
如果需要处理超大数(超过long long范围),需要使用字符串进行逐位计算的算法。这里展示的是最常用的基本实现方法。