In this tutorial, you will learn how to write a C++ Program to convert a given decimal number to binary using bitset library.
C++ Convert Decimal to Binary
To convert decimal number to binary, use std::bitset. bitset stores bits, and we can convert this into a string.
We need to set the number of bits while using bitset as shown in the following.
</>
Copy
bitset<number_of_bits>(decimal_number)
Program
In the following program, we read a number into n
(decimal value), and find its binary (16 bits length) using std::bitset.
main.cpp
</>
Copy
#include <iostream>
#include <bitset>
using namespace std;
int main() {
int n;
cout << "Enter a decimal number : ";
cin >> n;
string binary = bitset<16>(n).to_string();
cout << "Binary : " << binary << endl;
}
Output
Enter a decimal number : 45
Binary : 0000000000101101
Program ended with exit code: 0
Enter a decimal number : 7
Binary : 0000000000000111
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to convert decimal to binary in C++ using std::bitset.