6.30小学期基础语法记录:十进制转二进制
⬆️ 十进制转换为二进制
✅ 方法一:使用 bitset
标准库提供了 bitset<N>,将十进制整数直接转为固定长度的二进制字符串:
#include <iostream>
#include <bitset>
using namespace std;
int main() {
int num = 23;
bitset<8> b(num); // 8 表示输出8位二进制
cout << b << endl; // 输出: 00010111
}
📌 优点:
- 简洁明了,适合调试或可视化。
- 可指定位数自动补零。
✅ 方法二:手动除以2(适合学习/控制格式)
#include <iostream>
#include <string>
using namespace std;
string decToBin(int n) {
string res;
if (n == 0) return "0";
while (n > 0) {
res = char('0' + n % 2) + res;
n /= 2;
}
return res;
}
int main() {
int num = 23;
cout << decToBin(num) << endl; // 输出: 10111
}
📌 优点:
- 控制力强,可以变形用于非标准输出。
- 易于扩展(如转八进制、十六进制等)。
✅ 方法三:使用 std::bitset + .to_string()(可组合使用)
#include <bitset>
#include <string>
#include <iostream>
using namespace std;
int main() {
int num = 5;
string binary = bitset<16>(num).to_string(); // 固定16位输出
cout << binary << endl; // 输出: 0000000000000101
}
你也可以 .substr() 截掉前导0:
string trimmed = binary.substr(binary.find('1'));
✅ 方法四:使用 std::stack(用于进制转换练习)
#include <iostream>
#include <stack>
using namespace std;
void decToBin(int n) {
stack<int> s;
if (n == 0) {
cout << 0;
return;
}
while (n > 0) {
s.push(n % 2);
n /= 2;
}
while (!s.empty()) {
cout << s.top();
s.pop();
}
}
int main() {
decToBin(23); // 输出: 10111
}
⚠️ 注意事项:
| 方法 | 适用场景 | 是否可指定长度 | 是否自动补0 |
|---|---|---|---|
bitset |
快速可视化/竞赛常用 | ✅ | ✅ |
| 手动除2 | 控制格式 / 学习 / 输出变形 | ✅ | ❌(需手动) |
.to_string |
配合字符串处理 / 去前导0 | ✅ | ✅ |
stack |
教学用途或进制转换入门 | ❌ | ❌ |
🎯 总结推荐:
- 🚀 想要最快最简洁:
bitset<64>(num)。 - 🎯 想要输出没有前导 0 的字符串:
bitset.to_string().substr(find('1'))或手写除法。 - 💡 进阶扩展:可以写成通用函数处理
int,long,unsigned等。

浙公网安备 33010602011771号