Related Tags

c++
communitycreator

How to convert a number from decimal to binary in C++

Vinisha Maheshwari

In this shot, we will discuss how to convert a number from decimal to binary in C++.

When we convert a decimal number to a binary number, we divide the number by two. Then, we divide the quotient by two. We repeat the process until the remainder becomes one.

Let’s look at the image below to better understand how this conversion works.

Conversion of Decimal number to Binary number

In the image above, the number is divided by two until the remainder becomes one. When the remainder is one, we write the values in reverse order, as shown in the image. For example, the value of a decimal $28$ in binary form is $11101$.

Take a look at the code snippet below to understand it better.

#include <iostream>
using namespace std;

int main() {
int decimal, binary = 0, remainder, product = 1;
cin >> decimal;
while (decimal != 0) {
remainder = decimal % 2;
binary = binary + (remainder * product);
decimal = decimal / 2;
product *= 10;
}
cout << "The number in the binary form is: " << binary ;
return 0;
}

Enter the input below

Convert a decimal number to its binary equivalent in C++

Explanation

Enter a number in the input section above.

• In line 5, we initialize the variables decimal, binary, remainder, and product.

• In line 6, we take decimal as input.

• From lines 7 to 12, we initialize a while loop. In the loop, we calculate the remainders and quotients to convert the decimal number to its binary equivalent, as shown above.

• In line 13, we print the output, i.e., the binary equivalent of the decimal number.

This way, we can convert the value of a decimal number to a binary number.

RELATED TAGS

c++
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time