×

Decimal to Binary in C++

What is the meaning of Decimal Numbers?

Decimal numbers 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 121, 654, 111, 0, 3, and so on.

What is the meaning of Binary Numbers?

Because it is either 0 or 1, a binary number is a base 2 number. Binary numbers are made up of 0 and 1 digit, such as 10001, 1001, 1111, 101110, and so on.

Example:

// C++ program to convert a decimal
// number to binary number
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ;
// function to convert decimal to binary
void decimalToBinary ( int n ) 
{
// array to store binary number
int binaryNumber [ 32 ] ;




// counter for binary array
int i = 0 ;
while ( n > 0 ) {




// storing remainder in binary array
binaryNumber [ i ] = n % 2 ;
n = n / 2 ;
i++ ;
}




// printing binary array in reverse order
for ( int j = i - 1 ; j >= 0 ; j-- )
cout << binaryNumber [ j ] ;
}
int main ( )
{
int n = 10 ;
decimalToBinary ( n ) ;
return 0 ;
}

OUTPUT:

1010

Explanation:

  • When 10 is divided by 2, the remainder is zero. As a result, arr [ 0 ] = 0.
  • Subtract 2 from 10. 10 divided by 2 is equal to 5 is the new number.
  • When you divide five by two, the remainder is 1. As a result, arr [ 1 ] = 1.
  • Subtract 2 from 5. 5 / 2 = 2 is the new number.
  • When 2 is divided by 2, the remainder is zero. As a result, arr [ 2 ] = 0.
  • Subtract 2 from 2. 2 / 2 = 1 is the new number.
  • When you divide 1 by 2, the remainder is 1. As a result, arr [ 3 ] = 1.
  • Subtract 1 from 2. 1 / 2 = 0 is the new number.
  • Since the number equals 0 reverse the order of the array. As a result, the binary equivalent is 1010.

NOTE: To do the following, we can utilize bitwise operators. Bitwise operators are quicker than the arithmetic operators used previously.

Another example but now using bitwise operator:

// C++program to Decimal to binary conversion
// using bitwise operator
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ; 
// Function that convert Decimal to binary
int decimalToBinary ( int n )
{
// Size of an integer is assumed to be 32 bits
for ( int i = 31 ; i > = 0 ; i-- ) {
int k = n >> i ;
if ( k & 1 )
cout << " 1 " ;
else
cout << " 0 " ;
}
}
// driver code
int main ( )
{
int n = 64 ;
decimalToBinary ( n ) ;
}

OUTPUT:

0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0

Explanation:

Even for tiny numbers, the loop iterates a constant (64) amount of times.

Better Approach for Decimal to Binary in C++

Using the right shift (> >) and And ( & ) operators, it's another quick way to convert Decimal to binary. We'll solely utilize Binary Operators here, which are often quite quick in calculation.

#include < bits/stdc++.h >
#include < stdlib >
#include < iostream >
using namespace std ; 
string DecimalToBinary ( int num )
{
string str ;
while ( num ) {
if ( num & 1 ) // 1
str += '1' ;
else // 0
str += '0' ;
num >>= 1 ; // Right Shift by 1
}
return str ;
}
void rev ( string str )
{
for ( int i = str.size ( ) - 1 ; i >= 0 ; i-- )
cout << str [ i ] ;
}
int main ( ) {
int num = 49 ;
cout << "Binary of number” << num << ” is: " ;
rev ( DecimalToBinary ( num ) ) ;
return 0 ;
}

OUTPUT:

Binary of Number 49 is 110001
………………………………………………
Process executed in 0.321 seconds
Press any key to continue.

Explanation:

Above code is found to be a better approach of converting decimal to binary in C++. Using a string function DecimalTobinary and passing the number we want to convert and also using a function called rev to reverse.


Related Topics

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

How to Reverse a String in C++ using While Loop

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer...

6 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.