- How positional notation works — the same idea that makes base 10 familiar, applied to base 2
- Why the loop uses
place *= 2instead of then /= 10that most digit programs use - How
n % 10extracts individual bits when the number is stored as anint - Why input validation matters — what happens if the user enters 1205, which isn't valid binary
- How the same approach converts octal and hexadecimal to decimal, just with a different multiplier
Positional Notation — The Heart of It
In base 10, the number 342 means 3×100 + 4×10 + 2×1. Each digit is multiplied by a place value — 1, 10, 100, 1000 — and the place value grows by a factor of 10 as you move left. The digit's position determines its weight.
In base 2, the same idea applies, but the place value grows by a factor of 2 instead of 10. So 1011 (binary) means 1×8 + 0×4 + 1×2 + 1×1 = 11 (decimal). The bits from left to right have place values 8, 4, 2, 1 — each double the previous. That's the whole story. Binary is just base-10 arithmetic with a different multiplier.
When you read a binary number as an int in C — say 1011 — the compiler stores it as the decimal integer 1011 (one thousand eleven). It doesn't "know" that you intended the bits to mean eleven in decimal. That's fine — the loop doesn't care what the number represents symbolically; it treats 1011 as four decimal digits, extracts them right-to-left (1, 1, 0, 1), and applies the correct place values (1, 2, 4, 8) to each. The digit "1" in the lowest place contributes 1×1=1; the "1" in the next place contributes 1×2=2; the "0" contributes 0; the "1" in the top place contributes 1×8=8. Sum: 11. Correct.
This is why the loop multiplies by 2, not 10. n /= 10 removes the last decimal digit of n — which happens to be the last bit of the binary representation. place *= 2 doubles the place value each iteration, matching the "each position is twice the previous" property of binary.
💡 In one line: for each digit d of the binary number (right to left), add d × place to a running total and double place. Start at place = 1.
Doubling the Place Value
Here's the algorithm in steps:
- Read the number as an integer, treating it as a decimal representation of the binary value.
- Set
decimal = 0andplace = 1. - Loop while
n > 0:- Extract the last digit:
digit = n % 10. - Add
digit × placetodecimal. - Double the place value:
place *= 2. - Remove the last digit:
n /= 10.
- Extract the last digit:
- Print
decimal.
The interesting line is place *= 2, which most of the previous digit programs didn't have. That line is what distinguishes base-2 conversion from base-10 understanding. For octal (base 8), you'd write place *= 8. For hex, place *= 16. The rest of the loop is identical, which is the point — base conversion is one pattern, repeated with a different multiplier.
| Binary | Calculation | Decimal | Note |
|---|---|---|---|
| 0 | 0 | 0 | Zero is zero in both bases |
| 1 | 1×1 | 1 | Single bit |
| 101 | 1×4 + 0×2 + 1×1 | 5 | Straightforward |
| 1011 | 1×8 + 0×4 + 1×2 + 1×1 | 11 | Four bits |
| 11111111 | 128+64+32+16+8+4+2+1 | 255 | Largest 8-bit value |
| 100000000 | 1×256 | 256 | First 9-bit value |
| 1111111111 | 1023 | 1023 | Largest 10-bit value |
Complete C Program
Program: binary to decimal using a while loop
#include <stdio.h>
int main(void) {
long long n; /* binary number can have up to 19 digits */
long long decimal = 0;
long long place = 1;
printf("Enter a binary number (digits 0 and 1 only): ");
if (scanf("%lld", &n) != 1 || n < 0) {
printf("Invalid input. Please enter a non-negative binary number.\n");
return 1;
}
long long temp = n; /* keep the original for display */
while (n > 0) {
int bit = n % 10;
if (bit != 0 && bit != 1) {
printf("Invalid binary number — the digit %d is not 0 or 1.\n", bit);
return 1;
}
decimal += bit * place;
place *= 2;
n /= 10;
}
printf("Binary %lld = Decimal %lld\n", temp, decimal);
return 0;
}
And here is the same program using the standard library function strtoll with base 2, which is the idiomatic way to convert binary to decimal if you can read the input as a string:
Alternative: use strtoll with base 2
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char input[64];
printf("Enter a binary number: ");
if (scanf("%63s", input) != 1) {
printf("Invalid input.\n");
return 1;
}
char *end;
long long decimal = strtoll(input, &end, 2);
if (*end != '\0') {
printf("Invalid binary number — %s is not a valid binary representation.\n", input);
return 1;
}
printf("Binary %s = Decimal %lld\n", input, decimal);
return 0;
}
The library version is shorter, handles leading whitespace, detects invalid digits automatically, and works correctly for binary numbers that exceed long long if you switch to a string-based big-number library. The manual loop is more instructive, which is why the assignment asks for it, but the library version is what you'd write in real code. Knowing both — and knowing when to prefer each — is more useful than either alone.
Program Output
Enter a binary number (digits 0 and 1 only): 1011
Binary 1011 = Decimal 11
A few more to try. Input 101 gives 5. Input 11111111 gives 255. Input 100000000 gives 256. Input 1111111111 gives 1023. Input 0 gives 0. Input 1 gives 1. Then try an invalid one like 1205 — the loop should detect the digit 2 (or 5) and reject the input with a clear error message.
Step-by-Step Explanation
Let's trace 1011 bit by bit.
1. Reading and validating input
scanf("%lld", &n) reads the binary number as a long long. The choice of long long (64-bit) rather than int (32-bit) is deliberate — binary numbers like 1111111111 (ten ones) fit in int, but 1111111111111111111 (nineteen ones) requires long long. Using the larger type costs nothing and avoids a class of errors.
The initial validation checks that scanf succeeded and that the input is non-negative. The loop will later validate individual digits — but the initial check catches "user typed letters" and "user typed a negative" before we get there.
2. Saving the original for display
The loop destroys n (divides it down to 0), so we save the original in temp for the final message. Without this, the output would say "Binary 0 = Decimal 11" — confusing for the user.
3. The main loop for 1011
Trace:
- Start:
n = 1011,decimal = 0,place = 1 - Iteration 1:
bit = 1,decimal += 1×1 = 1,place = 2,n = 101 - Iteration 2:
bit = 1,decimal += 1×2 = 3,place = 4,n = 10 - Iteration 3:
bit = 0,decimal += 0×4 = 3,place = 8,n = 1 - Iteration 4:
bit = 1,decimal += 1×8 = 11,place = 16,n = 0 - Loop exits — final
decimal = 11
The accumulated value 11 is exactly 1×1 + 1×2 + 0×4 + 1×8 = 11, which matches the formula.
4. Why n % 10 gets bits, not decimal digits
This is subtle. The number 1011 as an int is one thousand eleven, in decimal. When you do 1011 % 10, you get 1 — the last decimal digit. When you do 1011 / 10, you get 101 — the number with its last decimal digit removed.
These same operations, applied to 1011, happen to extract the binary digits of the number we intended as binary. Why? Because the digits of "1011" (as a decimal string) are also the bits of "1011" (as binary). The operation n % 10 gives the last character of the decimal representation — which happens to be the last bit of the binary representation, because the decimal string and the intended binary string are identical.
So the digit "1" we extract, and the place value 1 we multiply it by, together compute 1×1 for the lowest bit — which is correct. It's an odd-looking coincidence that rests on the fact that "1011" as a decimal string and "1011" as a binary string have the same character sequence. If you accidentally stored the number as 1011 decimal (one thousand eleven) and treated it as binary, you'd get a completely wrong result — the loop assumes the input's character sequence is the binary representation, not the decimal number 1011.
5. Input validation
The check if (bit != 0 && bit != 1) rejects inputs like 1205 or 4521 that contain digits other than 0 and 1. Without it, the program would silently compute something (for 1205, it would compute 1×1 + 0×2 + 2×4 + 1×8 = 1 + 0 + 8 + 8 = 17, treating "2" as a bit) that looks like a valid result but is meaningless. Clear rejection is better than silent garbage.
6. Overflow considerations
Both n and decimal are long long, so the program handles up to 19-digit binary numbers (since long long max is about 9.2×1018, which has 19 digits). For binary numbers longer than 19 digits, you'd need a big-number library or string manipulation. For the assignment, 19 digits is plenty — that's a binary number up to about 524287 in decimal, way more than any exam problem will ask for.
7. Why the library version is worth knowing
The manual loop is instructive, but the strtoll version is what production code usually uses. It handles invalid digits automatically (returning 0 and setting end to point at the invalid character), supports any base from 2 to 36, and doesn't require the caller to validate digits manually. The assignment asks for the loop version, so that's what the main program shows — but knowing that strtoll(input, NULL, 2) is a one-line solution makes you a more efficient programmer.
🎯 Remember this: each bit d contributes d × place to the decimal value, where place starts at 1 and doubles with each bit processed (right to left). The loop extracts bits with n % 10, shrinks with n /= 10, and doubles place. For octal or hexadecimal, just change the multiplier — the structure stays the same.
Frequently Asked Questions
1. Why does the loop use place *= 2 instead of place *= 10?
Because binary digits have place values that double with each position, not multiply by ten. In base 2, the rightmost bit is 1, the next is 2, the next is 4, the next is 8 — each is twice the previous. In base 10, they'd be 1, 10, 100, 1000. If you accidentally wrote place *= 10, the loop would compute the decimal value of the decimal representation of the digits, which for input 1011 would give 1×1 + 1×10 + 0×100 + 1×1000 = 1011 — the original number, not the binary-to-decimal conversion. The whole point of base conversion is using the right multiplier.
2. What if the user types 12 or 1205 instead of binary?
The program rejects it — the digit-level check if (bit != 0 && bit != 1) catches any digit that isn't 0 or 1. Without this check, the program would silently produce wrong results: for 1205, it would compute 1×1 + 0×2 + 2×4 + 1×8 = 17, treating "2" as if it were a valid binary digit. Even worse, for something like 99, it would compute nonsense. The validation makes the input contract explicit and prevents silent errors.
3. Why use long long instead of int?
Because binary numbers require many digits to express even modest decimal values. A 32-bit int can hold up to about 2.1 billion, but a binary representation of that number has 31 digits — longer than int can represent as a decimal number (10 digits). long long handles up to 19 digits, which covers binary numbers up to 219 − 1 = 524287. For most educational exercises, this is plenty. For larger binary numbers, you'd need strings or a big-number library.
4. Why does n % 10 extract a bit rather than a decimal digit?
It extracts a decimal digit — but for a binary number stored as an int, the decimal digits happen to be the binary digits. The number 1011 as an int is one thousand eleven; its decimal digits are 1, 1, 0, 1 — which happen to be the same as the bits of "1011" as a binary string. This is a coincidence of the representation: the user typed "1011" as a decimal literal, and we're treating that literal as if it were a binary digit string. The arithmetic works out because the characters align.
5. Can I convert to octal or hexadecimal the same way?
Yes — just change the multiplier. For octal, use place *= 8 and validate that digits are 0–7. For hexadecimal, use place *= 16 and use letters A–F or an equivalent scheme. But hexadecimal has a wrinkle: the letters A–F aren't decimal digits, so you can't read "1A3F" as an int. You'd need to read it as a string and process characters, converting each to its hex value. The binary case works with int input only because every binary digit happens to be a valid decimal digit.
6. Is there a library function for binary to decimal?
Yes: strtoll(input, NULL, 2). The third argument specifies the base, so passing 2 converts from binary. strtoll("1011", NULL, 2) returns 11. The function is more robust than the manual loop (handles whitespace, detects overflow, reports where parsing stopped) and supports bases from 2 to 36. For production code, use strtoll. For learning the algorithm, use the manual loop — that's what the assignment asks for, and it's a great exercise in understanding how positional notation works.
💡 Tip: After this program works, try the reverse conversion (decimal to binary) using the same loop skeleton — the multiplier becomes 2 instead of 10, but in a different place. You'll see how the two conversions mirror each other. Then try octal and hex conversions to see the pattern generalise. The insight you're building isn't "how to convert binary to decimal" — it's "how positional notation works, and how to convert between any two bases."