C Program to Convert Binary to Decimal Number
decimal = decimal * 2 + (binary_digit - '0') inside a loop.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <string.h> int main() { char binary[65]; int decimal = 0; printf("Enter a binary number: "); scanf("%64s", binary); for (int i = 0; i < strlen(binary); i++) { decimal = decimal * 2 + (binary[i] - '0'); } printf("Decimal: %d\n", decimal); return 0; }
Dry Run
Let's trace the binary number '1101' through the code
Initialize decimal
decimal = 0
Process first digit '1'
decimal = 0 * 2 + (1) = 1
Process second digit '1'
decimal = 1 * 2 + (1) = 3
Process third digit '0'
decimal = 3 * 2 + (0) = 6
Process fourth digit '1'
decimal = 6 * 2 + (1) = 13
| Iteration | Binary Digit | Decimal Value |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 0 | 6 |
| 4 | 1 | 13 |
Why This Works
Step 1: Reading input as string
We read the binary number as a string to process each digit individually.
Step 2: Converting digits to decimal
Each digit is converted from character to integer by subtracting '0', then added to the decimal total after multiplying the current total by 2.
Step 3: Accumulating result
Multiplying the current decimal value by 2 shifts it left by one binary place, then adding the digit adds the current bit value.
Alternative Approaches
#include <stdio.h> #include <string.h> #include <math.h> int main() { char binary[65]; int decimal = 0, length; printf("Enter a binary number: "); scanf("%64s", binary); length = strlen(binary); for (int i = 0; i < length; i++) { if (binary[i] == '1') { decimal += (int)pow(2, length - i - 1); } } printf("Decimal: %d\n", decimal); return 0; }
#include <stdio.h> #include <string.h> int main() { char binary[65]; int decimal = 0; printf("Enter a binary number: "); scanf("%64s", binary); for (int i = 0; i < strlen(binary); i++) { decimal = (decimal << 1) | (binary[i] - '0'); } printf("Decimal: %d\n", decimal); return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each binary digit once in a loop, so the time complexity is O(n), where n is the length of the binary string.
Space Complexity
The program stores the binary number as a string, so space complexity is O(n). The decimal variable uses constant space.
Which Approach is Fastest?
The bit shifting method is generally fastest because it uses low-level operations without function calls, while the pow() method is slower due to repeated power calculations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Multiplying by 2 and adding digit | O(n) | O(n) | Simple and clear for beginners |
| Using pow() function | O(n) | O(n) | Explicit power calculation but slower |
| Bit shifting | O(n) | O(n) | Efficient and suitable for binary operations |