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

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 2828 in binary form is 1110111101.

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;
// Since the data type is int, it can only accept values up to 1023 before switching to long.
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

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.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved