Convert Binary to Decimal in C
Last Updated :
24 Aug, 2023
In this article, we will learn how to write a C program to convert the given binary number into an equivalent decimal number. Binary numbers are expressed in base 2 ( 0, 1 ) and decimal numbers are expressed in base 10 ( 0-9 ).
Algorithm to Convert Binary Numbers to Decimal
- The idea is to extract the last digit of the binary number by performing the modulo operation ( % ) and store it in a variable last_digit and remove the last digit from the binary number by dividing by 10.
- Update the decimal value by multiplying last_digit with the current base value and adding it to dec_value.
- Update the base value by multiplying it by 2 to represent the next power of 2 for the next digit.
- Repeat these steps until are digits of the binary number are processed.
- Return the variable dec_value that stores the decimal value.
The below diagram explains how to convert ( 1010 ) to an equivalent decimal value:
C Program to Convert Binary Number to Decimal
C
#include <stdio.h>
int binaryToDecimal( int n)
{
int num = n;
int dec_value = 0;
int base = 1;
int temp = num;
while (temp) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 2;
}
return dec_value;
}
int main()
{
int num = 10101001;
printf ( "%d" , binaryToDecimal(num));
}
|
Complexity Analysis
- Time complexity: O( log n)
- Auxiliary Space: O(1)
Note: In the above program, we represented a binary number as integer value with base 10 as binary numbers are not directly supported by C language.
Refer to the complete article Program for Binary To Decimal Conversion for more details!
Related Articles
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...