1. 程式人生 > >C++中十進位制數轉換為二進位制數

C++中十進位制數轉換為二進位制數

在 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; }