Decimal to Binary Conversion in C, C++, Java, and Python
Four implementations to convert decimal to binary in C, C++, Java, and Python, with the algorithm, worked examples, and complexity analysis.
Decimal-to-binary conversion appears in placement coding rounds at service-tier and mid-tier companies, and the expected approach is always the manual algorithm.
The built-in alternatives are faster to write, but interviewers want to see that you understand the binary number system before you reach for them. This article covers the algorithm first, then shows complete implementations in C, C++, Java, and Python.
The Algorithm: Repeated Division by 2
Binary is base 2. Every decimal number can be expressed as a sum of powers of 2. The conversion algorithm extracts each binary digit by repeatedly dividing the number by 2 and recording the remainder.
Worked example: decimal 15 to binary.
- Step 1: 15 ÷ 2 = 7, remainder 1
- Step 2: 7 ÷ 2 = 3, remainder 1
- Step 3: 3 ÷ 2 = 1, remainder 1
- Step 4: 1 ÷ 2 = 0, remainder 1
- Remainders collected (LSB to MSB): 1, 1, 1, 1
- Reversed (MSB first): 1111
- Verification: 1×8 + 1×4 + 1×2 + 1×1 = 15
Worked example: decimal 19 to binary.
- Step 1: 19 ÷ 2 = 9, remainder 1
- Step 2: 9 ÷ 2 = 4, remainder 1
- Step 3: 4 ÷ 2 = 2, remainder 0
- Step 4: 2 ÷ 2 = 1, remainder 0
- Step 5: 1 ÷ 2 = 0, remainder 1
- Remainders collected: 1, 1, 0, 0, 1
- Reversed: 10011
- Verification: 1×16 + 0×8 + 0×4 + 1×2 + 1×1 = 19
The algorithm in four steps:
- Input the decimal number n.
- While n is greater than 0, compute
n % 2and store the remainder. Then divide:n = n / 2. - When n reaches 0, all bits are collected, but in reverse order (LSB first).
- Output the bits in reversed order to get the final binary string.
Implementation in C
The C approach stores remainders in an integer array, then prints the array in reverse.
#include <stdio.h>
void decimal_to_binary(int n) {
if (n == 0) {
printf("0\n");
return;
}
int bits[32];
int count = 0;
while (n > 0) {
bits[count++] = n % 2;
n /= 2;
}
for (int i = count - 1; i >= 0; i--) {
printf("%d", bits[i]);
}
printf("\n");
}
int main() {
decimal_to_binary(15); /* Output: 1111 */
decimal_to_binary(19); /* Output: 10011 */
decimal_to_binary(0); /* Output: 0 */
return 0;
}
The array size of 32 covers any non-negative 32-bit integer. The n = 0 special case is handled before the loop because the while (n > 0) condition would skip the loop body entirely, producing no output.
This array-reversal technique is the same pattern that comes up in common array traversal problems: store results forward during collection, read them backward on output.
Implementation in C++
The C++ version builds the binary string by prepending each new remainder to the front, which avoids the explicit reversal step.
#include <iostream>
#include <string>
using namespace std;
string decimal_to_binary(int n) {
if (n == 0) return "0";
string result = "";
while (n > 0) {
result = to_string(n % 2) + result;
n /= 2;
}
return result;
}
int main() {
cout << decimal_to_binary(15) << endl; // 1111
cout << decimal_to_binary(19) << endl; // 10011
return 0;
}
The standard library also provides std::bitset, which converts any integer to a fixed-width binary string in one call. bitset<8>(15).to_string() produces "00001111", which is 8 characters wide and zero-padded on the left. The manual loop above produces "1111" with no padding. For placement tests that specify a fixed-width output, the bitset approach is convenient; for tests that ask for minimum-width representation, the loop is cleaner.
Implementation in Java
Java’s StringBuilder makes in-place insertion at index 0 practical here.
public class DecimalToBinary {
public static String manualBinary(int n) {
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
while (n > 0) {
sb.insert(0, n % 2);
n /= 2;
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(manualBinary(15)); // 1111
System.out.println(manualBinary(19)); // 10011
System.out.println(Integer.toBinaryString(15)); // 1111 (built-in)
}
}
The Integer.toBinaryString(n) built-in produces the same minimum-width binary string without any prefix. Both the manual approach and the built-in run in O(log n). In a competitive coding environment where library calls are allowed, the built-in is fine. In a proctored placement test where you are expected to demonstrate understanding, write the manual version.
Implementation in Python
The same algorithm compresses to six lines in Python, and a one-liner built-in also exists.
def decimal_to_binary(n):
if n == 0:
return "0"
result = ""
while n > 0:
result = str(n % 2) + result
n //= 2
return result
print(decimal_to_binary(15)) # 1111
print(decimal_to_binary(19)) # 10011
print(bin(15)[2:]) # 1111 (built-in, strips the '0b' prefix)
Python’s bin() built-in returns a string like "0b1111". The [2:] slice removes the "0b" prefix. This is the idiomatic approach in production code. The manual loop is what placement tests expect when they ask for the algorithm.
The string-prepend pattern here mirrors the reversal technique used in a palindrome check: build the string in reverse as you go, so no second pass is needed to flip it.
Complexity, Edge Cases, and Placement Context
Time and Space Complexity
- Time: O(log n), where n is the input decimal value. The loop divides n by 2 on each pass, running once per bit in the binary representation.
- Space: O(log n) for the result string or array. In the C version, the
bitsarray holds at most 32 elements for a 32-bit integer input.
Edge Cases to Handle
Three inputs catch most off-by-one errors:
- n = 0: The while loop body never executes for zero. Handle it as a special case before the loop, as shown in all four implementations above.
- Negative inputs: The standard algorithm assumes non-negative integers. Placement tests specify “given a non-negative integer” for this reason. Negative numbers need a two’s complement representation, which is a separate problem.
- Large inputs: For values beyond a 32-bit int, Java’s
longtype or Python’s arbitrary-precision integers handle the extension without changing the algorithm.
Where This Appears in Placement Tests
Decimal-to-binary conversion comes up in three ways in Indian IT placement rounds:
- As a standalone coding problem in TCS NQT and Infosys InfyTQ.
- As part of a bitwise-operations question where you need the binary representation to count set bits or verify a power of two.
- As the setup for a follow-up on two’s complement or sign extension.
For the broader set of topics that appear in technical rounds alongside this problem, see data structures interview questions.
Placement coding rounds consistently expect you to write the algorithm from scratch rather than invoke a built-in. Once you can implement decimal-to-binary in four languages without thinking about it, the natural next step is building something that calls it: a number-system converter that accepts any input base via an HTTP request. TinkerLLM has guided projects that start exactly there, and the entry plan costs ₹299.
Primary sources
Frequently asked questions
What does the binary representation of 0 look like?
The binary representation of 0 is simply '0'. The while (n > 0) loop exits immediately for n = 0, so all four implementations shown here handle it as a special case before the loop.
Does the repeated-division algorithm work for negative numbers?
Not directly. The while (n > 0) condition halts immediately for negative inputs. Negative integers use two's complement representation in hardware. For placement tests, assume positive inputs unless the problem explicitly says otherwise. In Java, Integer.toBinaryString handles two's complement automatically for negative values.
What is the fastest way to convert decimal to binary in Python?
Use bin(n)[2:] — it is a single O(log n) call that delegates to C internals. The manual while-loop approach in pure Python is functionally equivalent but slightly slower by a constant factor at runtime.
Why do interviewers ask you to write this manually when languages have built-ins?
The manual implementation tests whether you understand the binary number system, not just whether you can call a library function. Most placement coding rounds at TCS NQT, Infosys InfyTQ, and similar tests score the algorithm. Understanding why it works distinguishes stronger candidates from those who memorised the syntax.
How many bits does the number 255 need in binary?
255 in binary is 11111111 — exactly 8 bits. You can verify: 2 raised to the power of 8 minus 1 equals 255. Any 8-bit unsigned integer fits between 0 (00000000) and 255 (11111111).
What is the time complexity of decimal-to-binary conversion?
O(log n), where n is the decimal input value. The while loop divides n by 2 on each iteration, so it runs exactly as many times as there are bits in n. For a 32-bit integer, the loop runs at most 32 times regardless of the input.
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)