# 如何在 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多年。他在自動測試、遠端測試及從耐久性測試中創建報告時磨練了自己的程式設計技能。他擁有電氣/ 電子工程背景，但他也擴展了自己的興趣到嵌入式電子、嵌入式程式設計以及前端和後端程式設計。