Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Decimal Number?
3.
What is Binary Number?
4.
Decimal to Binary Conversion Algorithm
5.
C++ Program to Convert Binary Number to Decimal
5.1.
Code
5.2.
C++
5.3.
Output
5.4.
Time Complexity
6.
C++ program to convert Decimal Number to Binary Number using Array
6.1.
C++
7.
Program to Convert Decimal Number to Binary in C++ Without using Array
7.1.
C++
8.
Program to convert Decimal Number to Binary in C++ using predefined functions
8.1.
Syntax
8.2.
Parameters
8.3.
Return Value
9.
Program to Convert Decimal Number to Binary in C++ using Bitset
9.1.
Decimal to Binary Conversion using std::bitset
9.2.
C++
10.
Frequently Asked Questions
10.1.
How do you convert decimals to binary in C++?
10.2.
How do you convert decimals to binary in c?
10.3.
How to convert decimal to binary in C++ using while loop?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

C++ Program to Convert Decimal to Binary

Author Ayushi Poddar
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Converting decimal numbers to binary is a key operation in computer science, and doing this in C++ offers both efficiency and clarity. Our focus here is on the "decimal to binary C++" conversion, a process integral to understanding data representation and manipulation in computing. 

C++ Program to Convert Decimal to Binary

This conversion is particularly important for those delving into the deeper aspects of programming, as it lays the groundwork for more complex operations and algorithms. We will delve into how C++ can be used to perform this conversion effectively, highlighting the language's suitability for such tasks.

What is Decimal Number?

As decimal number range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two digits is a decimal number, such as 223, 585, 192, 0, 7, and so on.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Binary Number?

A binary number is either 0 or 1,  and that is the reason why a binary number is a base 2 number. Binary numbers are made up of 0 and 1 digits, such as 1001, 101, 11111, 101010, and so on.

Decimal Binary
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

Decimal to Binary Conversion Algorithm

Step 1: Use the percent (modulus operator) to divide the integer by two and put the residue in an array.

Step 2: Divide the number by 2 using the “/ “(division operator)

Step 3: Keep repeating steps 1 and 2 until the total is larger than zero.

C++ Program to Convert Binary Number to Decimal

Let's now see the C++ example to convert decimal to binary.

Code

  • C++

C++

#include <iostream>  
using namespace std; 
int main() 

    int a[10], n, i;   
    cout<<"Enter the number in the decimal system: ";  //Taking user input
    cin>>n;   
    for(i=0; n>0; i++)   
    {   
         a[i]=n%2;  //Storing the remainders into an array
         n= n/2; 
     }   
     cout<<"The binary equivalent of the number is ";   
     for(i=i-1 ;i>=0 ;i--)   
     {   
          cout<<a[i];  //Printing the binary equivalent
      }
}

Output

Enter the number in the decimal system: 15
The binary equivalent of the number is 1111

Time Complexity

The time complexity of this code is O(log n), where n is the input decimal number.

You can try by yourself with the help of online C++ Compiler.

C++ program to convert Decimal Number to Binary Number using Array

This program converts a decimal number to its binary representation using an array to store the binary digits. It takes a decimal number as input. Create an array to hold the binary digits. Loop through the decimal number, continuously dividing it by 2 and storing the remainder (binary digits) in the Array. Print the binary representation by iterating through the Array in reverse order. For example

  • C++

C++

#include <iostream>
using namespace std;

void decimalToBinary(int decimalNum) {
// Assuming 8-bit binary representation
const int size = 8;
int binaryArray[size];
int index = 0;

// Convert decimal to binary
while (decimalNum > 0 && index < size) {
binaryArray[index] = decimalNum % 2;
decimalNum /= 2;
index++;
}

// Display the binary representation
cout << "Binary representation: ";
for (int i = index - 1; i >= 0; i--) {
cout << binaryArray[i];
}
cout << endl;
}

int main() {
int decimalNumber;

cout << "Enter a decimal number: ";
cin >> decimalNumber;

// Check for negative input
if (decimalNumber < 0) {
cout << "Please enter a non-negative decimal number." << endl;
return 1;
}

// Calling the function
decimalToBinary(decimalNumber);

return 0;
}

Output

Enter a decimal number: 34
Binary representation: 100010

Program to Convert Decimal Number to Binary in C++ Without using Array

C++ Program converts a decimal number to its binary number without using an array. It directly prints the binary digits. It takes a decimal number as input and uses a loop to extract and print the binary digits directly by performing bitwise operations (& and >>) on the decimal number. For example

  • C++

C++

#include <iostream>
using namespace std;

void decimalToBinary(int decimalNum) {
if (decimalNum == 0) {
cout << "Binary representation: 0" << endl;
return;
}

int binaryDigit;
int binaryResult = 0;
int base = 1;

// Convert decimal to binary
while (decimalNum > 0) {
binaryDigit = decimalNum % 2;
binaryResult += binaryDigit * base;
decimalNum /= 2;
base *= 10;
}

// Display the binary representation
cout << "Binary representation: " << binaryResult << endl;
}

int main() {
int decimalNumber;

cout << "Enter a decimal number: ";
cin >> decimalNumber;

// Check for negative input
if (decimalNumber < 0) {
cout << "Please enter a non-negative decimal number." << endl;
return 1;
}

// Calling the function
decimalToBinary(decimalNumber);

return 0;
}

Output

Enter a decimal number: 49
Binary representation: 110001

Program to convert Decimal Number to Binary in C++ using predefined functions

Using built-in functions, C ++ Program converts a decimal number to its binary representation. It takes a decimal number as input and the bitset class from the C++ Standard Library, providing convenient binary representation methods. It creates a bitset object using the decimal number and binary representation length. Print the binary representation using the to_string() method of the bitset object.

Syntax

bitset<N> decimalToBinary(int decimalNum);

Parameters

It takes decimalNum, an integer representing the decimal number to be converted.

Return Value

Returns a bitset<N>, where N is the number of bits specified in the bitset (e.g., bitset<8> for an 8-bit binary representation).

Program to Convert Decimal Number to Binary in C++ using Bitset

C++ program converts a decimal number to its binary representation using the bitset class. However, it shows a different approach, taking a decimal number as input. And convert the decimal number to a bitset object, specify the number of bits required for the binary representation, and then print the binary representation using the to_string() method of the bitset object.

Also see, Application of Oops

Decimal to Binary Conversion using std::bitset

Decimal to binary conversion using std::bitset in C++ allows for an efficient and straightforward way to represent decimal numbers as binary. This standard library feature creates a fixed-size sequence of bits and assigns the decimal value, automatically converting it to binary. Here's a simple example:

  • C++

C++

#include <bitset>
#include <iostream>
int main() {
int decimal = 10;
std::bitset<8> binary(decimal);
std::cout << "Binary representation of " << decimal << " is " << binary << std::endl;
return 0;
}

Output

Binary representation of 10 is 00001010

Frequently Asked Questions

How do you convert decimals to binary in C++?

You can convert decimals to binary in C++ by using bitset or bitwise operations like >>. For example: bitset<8>(decimal).to_string().

How do you convert decimals to binary in c?

You can convert decimals to binary in C by implementing a loop with bitwise operations or divide-by-2.

How to convert decimal to binary in C++ using while loop?

To convert decimal to binary in C++ you can also use a while loop along with bitwise operations or division by 2.

Conclusion

This article discussed the C++  program to convert a decimal to binary. We can use bitwise operations or standard library functions like bitset to convert decimal to binary. Understanding this concept empowers programmers to efficiently handle decimal-to-binary conversions, a fundamental skill in algorithmic problem-solving.

 

Recommended problems -

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive Programming, and many more! If you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Previous article
C++Program to Convert Octal to Binary
Next article
C++ Program to Convert Octal Number to Decimal
Live masterclass