Loop Assignment 14 — Binary to Decimal Conversion Using While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Convert a Binary Number to Decimal Using a While Loop

📑 On this page:
  • Positional Notation — The Heart of It
  • Doubling the Place Value
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How positional notation works — the same idea that makes base 10 familiar, applied to base 2
  • Why the loop uses place *= 2 instead of the n /= 10 that most digit programs use
  • How n % 10 extracts individual bits when the number is stored as an int
  • 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.

Diagram showing the binary number 1011 broken into place values 8, 4, 2, 1 with each bit contributing to a decimal sum of 11

Doubling the Place Value

Here's the algorithm in steps:

  1. Read the number as an integer, treating it as a decimal representation of the binary value.
  2. Set decimal = 0 and place = 1.
  3. Loop while n > 0:
    • Extract the last digit: digit = n % 10.
    • Add digit × place to decimal.
    • Double the place value: place *= 2.
    • Remove the last digit: n /= 10.
  4. 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
000Zero is zero in both bases
11×11Single bit
1011×4 + 0×2 + 1×15Straightforward
10111×8 + 0×4 + 1×2 + 1×111Four bits
11111111128+64+32+16+8+4+2+1255Largest 8-bit value
1000000001×256256First 9-bit value
111111111110231023Largest 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:

  1. Start: n = 1011, decimal = 0, place = 1
  2. Iteration 1: bit = 1, decimal += 1×1 = 1, place = 2, n = 101
  3. Iteration 2: bit = 1, decimal += 1×2 = 3, place = 4, n = 10
  4. Iteration 3: bit = 0, decimal += 0×4 = 3, place = 8, n = 1
  5. Iteration 4: bit = 1, decimal += 1×8 = 11, place = 16, n = 0
  6. 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."

📖 Related Tutorials

  • 15. Convert an Octal Number to Decimal Using a For Loop
  • 16. Convert a Decimal Number to Octal Using a Do-While Loop
  • 17. Count the Number of 1s in Binary Representation Using a While Loop
  • 18. Convert a Hexadecimal String to Decimal Using a For Loop
  • 6. Count the Digits in an Integer Using a While Loop
  • While Loop
  • Bitwise Operators
  • All 30 Loop Assignments

Previous Topic: -->> 13. Check Whether All Digits of an Integer Are Even Using a For Loop   ||   Next Topic: -->> 15. Convert an Octal Number to Decimal Using a For Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.