Binary to Decimal Conversion: Algorithm, Code, and Edge Cases
Positional weighting, three verified worked examples, and C, Python, Java implementations, including built-in functions and signed-number edge cases.
Binary-to-decimal conversion uses positional weighting: each bit multiplies its value (0 or 1) by a power of 2 determined by its position in the sequence.
That one sentence is the whole algorithm. The rest of this article is the implementation.
How Positional Weighting Works
Every binary digit (bit) occupies a position numbered from right to left, starting at 0. The bit’s decimal contribution equals its value multiplied by 2 raised to its position number.
For the 4-bit string 1111:
| Position | Bit | Calculation | Contribution |
|---|---|---|---|
| 3 | 1 | 1 × 2³ | 8 |
| 2 | 1 | 1 × 2² | 4 |
| 1 | 1 | 1 × 2¹ | 2 |
| 0 | 1 | 1 × 2⁰ | 1 |
Total: 8 + 4 + 2 + 1 = 15
Note: the legacy FACE Prep article on this topic listed 1 × 2^3 = 6 and then 1 + 2 + 4 + 6 = 15. Both intermediate values were wrong. The correct calculation is 1 × 8 = 8, giving 1 + 2 + 4 + 8 = 15.
The table structure above scales to any bit width. An 8-bit binary number has positions 0 through 7, with maximum contribution 1 × 2^7 = 128. A 16-bit number’s leftmost bit contributes at most 1 × 2^15 = 32768.
Step-by-Step Worked Examples
Three examples, derived from first principles.
Example 1: 1010
- Position 3: 1 × 2³ = 8
- Position 2: 0 × 2² = 0
- Position 1: 1 × 2¹ = 2
- Position 0: 0 × 2⁰ = 0
- Decimal result: 8 + 0 + 2 + 0 = 10
Verification: int('1010', 2) in Python returns 10. ✓
Example 2: 11001011
- Position 7: 1 × 128 = 128
- Position 6: 1 × 64 = 64
- Position 5: 0 × 32 = 0
- Position 4: 0 × 16 = 0
- Position 3: 1 × 8 = 8
- Position 2: 0 × 4 = 0
- Position 1: 1 × 2 = 2
- Position 0: 1 × 1 = 1
- Decimal result: 128 + 64 + 8 + 2 + 1 = 203
Example 3: 100000000 (9 bits)
- Only bit 8 is set: 1 × 2^8 = 256
This is 2^8, or 0x100 in hexadecimal. Placement aptitude questions often use a single set bit like this to test whether you know the powers-of-2 sequence by heart.
Implementation: Loop and Horner’s Method
Positional Loop (right-to-left, integer input)
The oldest approach treats the binary input as an integer and peels off its digits using modulo 10. This works only when the binary input fits in a native integer type.
#include <stdio.h>
#include <math.h>
int binaryToDecimal(long long binary) {
int decimal = 0, power = 0;
while (binary != 0) {
int bit = binary % 10; /* extract rightmost decimal digit */
decimal += bit * (int)pow(2, power);
power++;
binary /= 10; /* shift right one decimal digit */
}
return decimal;
}
int main(void) {
printf("%d\n", binaryToDecimal(1111)); /* 15 */
printf("%d\n", binaryToDecimal(1010)); /* 10 */
printf("%d\n", binaryToDecimal(11001011)); /* 203 */
return 0;
}
The long long type holds up to 18 decimal digits, so binaries up to 18 bits fit. Beyond that, use the string approach below.
This digit-extraction pattern is structurally identical to the program to find the sum of digits. It uses the same % 10 and / 10 loop, with accumulation by position rather than by direct sum.
Horner’s Method (left-to-right, string input)
Horner’s method avoids the power-of-2 computation entirely. It processes bits from left to right, doubling the running total at each step:
result = result × 2 + current_bit
Applied to 1111:
- Start: result = 0
- Bit ‘1’: result = 0 × 2 + 1 = 1
- Bit ‘1’: result = 1 × 2 + 1 = 3
- Bit ‘1’: result = 3 × 2 + 1 = 7
- Bit ‘1’: result = 7 × 2 + 1 = 15
/* C string input, Horner's method */
int binaryStringToDecimal(const char *binary) {
int result = 0;
while (*binary) {
result = result * 2 + (*binary - '0');
binary++;
}
return result;
}
# Python, Horner's method
def binary_to_decimal(binary_str: str) -> int:
result = 0
for bit in binary_str:
result = result * 2 + int(bit)
return result
// Java, Horner's method
public static int binaryToDecimal(String binary) {
int result = 0;
for (int i = 0; i < binary.length(); i++) {
result = result * 2 + (binary.charAt(i) - '0');
}
return result;
}
The string-based approach is preferred in practice. It handles arbitrary length, avoids the implicit decimal-number representation, and its space complexity is O(1), since the result accumulates in a single integer variable regardless of input length.
Built-in Conversion Functions
All three major placement languages provide a one-liner for this conversion.
Python
Python’s int() built-in accepts a second argument for the source base:
decimal = int("1111", 2) # 15
decimal = int("11001011", 2) # 203
decimal = int("0b1111", 2) # 15 — 0b prefix accepted
Passing a non-binary character raises ValueError. Wrap in a try/except block for production code.
Java
Integer.parseInt(String s, int radix) is the Java standard library equivalent:
int decimal = Integer.parseInt("1111", 2); // 15
int decimal = Integer.parseInt("11001011", 2); // 203
For binary strings longer than 31 bits, use Long.parseLong(s, 2) instead. Integer.parseInt throws NumberFormatException on overflow.
C
The C standard library function strtol (string-to-long) accepts a base parameter:
#include <stdlib.h>
char *end;
long decimal = strtol("1111", &end, 2); /* 15 */
long decimal = strtol("11001011", &end, 2); /* 203 */
The &end pointer points to the first character that was not consumed. Check *end == '\0' to confirm the full string was valid binary. On overflow, strtol returns LONG_MAX and sets errno to ERANGE.
Edge Cases That Trip Up Beginners
Integer Overflow
The single biggest bug in placement coding rounds. An int in C and Java holds 32 bits, which means binary inputs longer than 31 bits (unsigned) or 30 bits (signed) will overflow silently in the positional-loop approach. The Horner string approach has the same problem; the overflow is in the accumulator, not the input representation.
Fix: use long long in C or Long.parseLong in Java. Python has no overflow concern; its integers are arbitrary precision.
Signed Two’s Complement
When the question specifies an n-bit signed integer, the most significant bit (MSB) has a negative weight. For 8-bit signed:
- Bit 7 contributes -128 (not +128)
- Remaining bits 6..0 contribute their usual positive values
So 10000001 in 8-bit signed two’s complement = -128 + 1 = -127, not +129.
This matters for programs that manipulate integer bits directly. The sign interpretation is a property of the type, not the bit pattern.
Leading Zeros
0001 is valid binary and equals 1. String-based implementations and all three built-in functions handle leading zeros correctly. No special case needed.
Invalid Input Characters
Any character other than ‘0’ and ‘1’ in the input is invalid binary. Python’s int(s, 2) and Java’s Integer.parseInt(s, 2) raise exceptions; C’s strtol stops at the first invalid character and sets *end to point to it. Always validate input before conversion in production code.
Horner’s left-to-right accumulation from the Implementation section above is the same arithmetic that transformer tokenisers use when encoding token IDs as binary-packed integers. If you want to run that tokenisation live, TinkerLLM provides a Python environment at ₹299 where you can inspect how raw integers flow through a tokeniser’s embedding table: the same result = result * 2 + bit pattern, applied at billion-parameter scale.
Primary sources
Frequently asked questions
What is positional notation in binary?
Positional notation assigns each digit a value based on its position. In binary, the rightmost bit has position 0 and contributes bit × 2^0. Each position to the left doubles the weight, so position 1 contributes bit × 2^1, position 2 contributes bit × 2^2, and so on.
How does Horner's method work for binary conversion?
Horner's method processes the binary string left-to-right. It maintains a running total: for each bit, it doubles the current total and adds the new bit. Starting at 0, processing 1011 gives 0 to 1 to 2 to 5 to 11. The final total is the decimal result.
What is the largest value a 32-bit unsigned integer can hold?
A 32-bit unsigned integer can hold values from 0 to 4,294,967,295 (which is 2 to the power of 32 minus 1). In binary, this is 32 ones.
How do I handle leading zeros in a binary string?
Leading zeros are harmless: they contribute 0 × 2^position = 0 to the total. Both int('0001', 2) in Python and Integer.parseInt('0001', 2) in Java return 1. The string-based implementations handle leading zeros correctly without special-casing.
How does signed two's complement affect binary-to-decimal conversion?
In two's complement, the most significant bit (MSB) has a negative weight. For an 8-bit signed integer, the MSB represents -128 rather than +128. So 10000001 in signed 8-bit equals -128 plus 1, which is -127, not +129. The built-in language conversions treat the string as unsigned unless you explicitly cast to a signed type.
What happens if I pass a non-binary string to int(s, 2) in Python?
Python raises a ValueError. For example, int('102', 2) throws ValueError: invalid literal for int() with base 2: '102'. Wrap the call in a try/except block to handle invalid input gracefully.
Is binary-to-decimal conversion asked in placement tests?
Yes. Number-system conversion (binary, octal, decimal, hexadecimal) is a standard topic in the aptitude sections at TCS, Infosys, Wipro, and Cognizant. Expect one to two questions in the quantitative section, and occasional C or Java coding questions in the technical round.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)