In this shot, we will discuss how to convert a number from binary to decimal in C++.
When we convert a binary number to a decimal number, we multiply each digit by ($2^n$).
Let’s look at the below image to understand how this conversion works.
In the above image, the binary number is multiplied by $2^n$ from the right side to the left side with the increasing $n$ that is $2^0$, $2^1$,$2^2$ and so on.
The value of binary number 10110
in decimal form is 22
.
Let’s look at the below code snippet to understand this better.
#include <iostream> using namespace std; int main() { int decimal = 0, binary, remainder, product = 1; cin >> binary; while (binary != 0) { remainder = binary % 10; decimal = decimal + (remainder * product); binary = binary / 10; product *= 2; } cout << "The number in the decimal notation is: " << decimal ; return 0; }
Enter the input below
Enter a binary number above in the input section.
In line 5, we initialize the variables decimal
, binary
, remainder
, and product
.
In line 6, we take binary
as input.
In lines 7 to 12, we initialize a while
loop. In the loop, we make the required calculations, as discussed in the above illustration, to convert the binary number to its decimal equivalent.
In line 13, we print the output, i.e., the decimal equivalent of the binary number.
RELATED TAGS
CONTRIBUTOR
View all Courses