Problem statement
Write a problem which takes a binary number from the user and convert them into a decimal number.
What is binary number and decimal number?
A binary number is consist of only 0’s and 1’s.
We can represent any number into the binary form.
Each digit is referred to as a bit.
Numbers from 2 to 9 are called as decimal numbers.
For example:
Decimal number | Binary number |
---|---|
0 | 0000 |
1 | 0001 |
2 | 0010 |
3 | 0011 |
4 | 0100 |
5 | 0101 |
6 | 0110 |
7 | 0111 |
8 | 1000 |
9 | 1001 |
In this way, we can convert any number into the binary number.
Program for converting binary to decimal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<stdio.h> int main() { int binary_number, decimal_number=0, rem, num,base=1; printf("Enter a binary number\n"); scanf("%d",&binary_number); num = binary_number; while (binary_number > 0) { rem = binary_number % 10; decimal_number = decimal_number + rem * base; binary_number = binary_number / 10 ; base = base * 2; } printf("Input binary number is %d\n", num); printf("Converted decimal number is %d",decimal_number); } |
Output:
1 2 3 4 |
Enter a binary number 101101 Input binary number is 101101 Converted decimal number is 45 |