在 C++ 中,我們可以利用下面的方法,将一個十進制數直接轉換為二進制數并輸出。
1、bitset<size_t len> 類型可以代表任意長度的二進制集合。
2、bitset<size_t len>() 構造函數可以将一個十進制數轉換為其二進制形式。
3、stream << bitset<size_t len> 被重載,可以自動輸出 bitset 的值。
#include <iostream>
#include <limits>
#include <bitset>
using namespace std;
int main()
{
/*
Use bitset to create a binary set.
numeric_limits<unsigned int>::digits is the binary length of type unsigned int.
use constructor : bitset<T>(unsigned int binary_length);
*/
cout << bitset<numeric_limits<unsigned int>::digits>(123) << endl;
return 0;
}