# 如何在 C++ 中把十进制转换为二进制

Jinku Hu 2023年10月12日

## 在 C++ 中使用自定义定义的函数将十进制数转换为二进制数

``````#include <iostream>

using std::cout;
using std::endl;
using std::string;

string toBinary(int n) {
string r;
while (n != 0) {
r += (n % 2 == 0 ? "0" : "1");
n /= 2;
}
return r;
}

int main() {
int number = 15;

cout << "decimal: " << number << endl;
cout << "binary : " << toBinary(number) << endl;

return EXIT_SUCCESS;
}
``````

``````decimal: 15
binary : 1111
``````

## 使用 `std::bitset` 类在 C++ 中把十进制数转换为二进制数

``````#include <bitset>
#include <iostream>

using std::bitset;
using std::cout;
using std::endl;
using std::string;

string toBinary(int n) {
string r;
while (n != 0) {
r += (n % 2 == 0 ? "0" : "1");
n /= 2;
}
return r;
}

int main() {
int number = 15;

bitset<32> bs1(toBinary(number));
cout << "binary:  " << bs1 << endl;
bitset<32> bs2(number);
cout << "binary:  " << bs2 << endl;

return EXIT_SUCCESS;
}
``````

``````binary:  00000000000000000000000000001111
binary:  00000000000000000000000000001111
``````

``````#include <bitset>
#include <iostream>

using std::bitset;
using std::cout;
using std::endl;
using std::string;

int main() {
int number = 15;

bitset<32> bs1(number);
cout << "binary:  " << bs1 << endl;
bitset<16> bs2(number);
cout << "binary:  " << bs2 << endl;
bitset<8> bs3(number);
cout << "binary:  " << bs3 << endl;
bitset<5> bs4(number);
cout << "binary:  " << bs4 << endl;
cout << endl;

return EXIT_SUCCESS;
}
``````

``````binary:  00000000000000000000000000001111
binary:  0000000000001111
binary:  00001111
binary:  01111
``````

`bitset` 类有几个有用的方法对其内容进行操作。这些方法可以用来反转集合的所有位（`flip` 函数）或 `reset`/`set` 序列中指定的位。还支持核心的二进制运算，如 `AND``OR``XOR``NOT``SHIFT`。我们在下面的例子中展示了其中的几个，但你可以看到 `bitset` 类的完整手册这里

``````#include <bitset>
#include <iostream>

using std::bitset;
using std::cout;
using std::endl;
using std::string;

int main() {
int number = 15;

bitset<32> bs(number);
cout << "binary : " << bs << endl;
cout << "flipped: " << bs.flip() << endl;
cout << "shift>4: " << (bs >>= 6) << endl;
cout << "shift<5: " << (bs << 2) << endl;
cout << "reset  : " << bs.reset() << endl;
cout << "set    : " << bs.set(16) << endl;

return EXIT_SUCCESS;
}
``````

``````binary : 00000000000000000000000000001111
flipped: 11111111111111111111111111110000
shift>4: 00000011111111111111111111111111
shift<5: 00001111111111111111111111111100
reset  : 00000000000000000000000000000000
set    : 00000000000000010000000000000000
``````

DelftStack.com 创始人。Jinku 在机器人和汽车行业工作了8多年。他在自动测试、远程测试及从耐久性测试中创建报告时磨练了自己的编程技能。他拥有电气/电子工程背景，但他也扩展了自己的兴趣到嵌入式电子、嵌入式编程以及前端和后端编程。