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