×

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

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

4 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes 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.