Placement Prep

Decimal to Binary in Python: 3 Methods Explained

Convert decimal numbers to binary in Python using bin(), format(), and a custom loop. Verified step-by-step algorithm, edge cases, and placement test tips.

By FACE Prep Team 4 min read
python decimal-to-binary placement-prep coding-practice number-systems python-programs

Python gives you three ways to convert a decimal integer to binary: the built-in bin() function, a manual division-by-2 loop, and the format() string formatter.

All three appear in placement coding rounds. The difference is not the output they produce but what each method demonstrates. Knowing when to use each (and how to implement the manual version from scratch) covers both “write the shortest solution” and “implement without built-ins” question types.

The division-by-2 algorithm

Binary is base 2. Every decimal number can be expressed as a sum of powers of 2. The division-by-2 algorithm finds the coefficient (0 or 1) for each power by repeatedly dividing the number and collecting remainders.

Walkthrough for 25:

  • Step 1: 25 divided by 2 gives 12 remainder 1
  • Step 2: 12 divided by 2 gives 6 remainder 0
  • Step 3: 6 divided by 2 gives 3 remainder 0
  • Step 4: 3 divided by 2 gives 1 remainder 1
  • Step 5: 1 divided by 2 gives 0 remainder 1
  • Read remainders bottom-to-top: 11001
  • Verify: 16 + 8 + 0 + 0 + 1 = 25. Correct.

One more: 14.

  • Step 1: 14 divided by 2 gives 7 remainder 0
  • Step 2: 7 divided by 2 gives 3 remainder 1
  • Step 3: 3 divided by 2 gives 1 remainder 1
  • Step 4: 1 divided by 2 gives 0 remainder 1
  • Read remainders bottom-to-top: 1110
  • Verify: 8 + 4 + 2 + 0 = 14. Correct.

This is the algorithm all three methods below implement. The code differs only in how it accumulates and returns the result.

Method 1: Python’s built-in bin() function

Python’s built-in bin() function takes an integer and returns its binary string representation prefixed with 0b.

number = int(input("Enter a decimal number: "))
print("Binary:", bin(number)[2:])

The [2:] slice removes the 0b prefix. For input 25, the output is 11001.

bin() is the fastest option for any placement question that permits built-in functions. One line. The only point of confusion is the prefix: [2:] handles it cleanly.

Negative numbers work too: bin(-25) returns '-0b11001'. Use bin(n)[2:] only when the input is guaranteed non-negative. Otherwise, check the sign explicitly before slicing.

Method 2: Custom function with a division loop

When a placement question asks to implement conversion without built-in functions, this is the version required. The function builds the binary string by collecting remainders in a list, then joins them in reverse.

def decimal_to_binary(num):
    if num == 0:
        return "0"
    binary_digits = []
    while num > 0:
        binary_digits.append(str(num % 2))
        num = num // 2
    return "".join(reversed(binary_digits))

number = int(input("Enter a decimal number: "))
print("Binary:", decimal_to_binary(number))

For input 25, the loop collects ['1', '0', '0', '1', '1'], reverses to ['1', '1', '0', '0', '1'], and joins to 11001.

The check for num == 0 is necessary. The while num > 0 loop body never executes for input 0, leaving binary_digits empty. Without the check, "".join(reversed([])) returns an empty string rather than "0".

Some placement questions phrase the problem as a recursive function. The recursive version prints each bit as the call stack unwinds, achieving the reverse naturally:

def decimal_to_binary_recursive(num):
    if num > 1:
        decimal_to_binary_recursive(num // 2)
    print(num % 2, end='')

number = int(input("Enter a decimal number: "))
decimal_to_binary_recursive(number)
print()

For input 25, the output is 11001. The print() at the end adds the newline that end='' suppresses during the recursive calls.

Method 3: Python’s format() and f-strings

Python’s format() function accepts a format specification. The 'b' specifier converts an integer to its binary string without the 0b prefix.

number = int(input("Enter a decimal number: "))
print("Binary:", format(number, 'b'))

The equivalent f-string:

number = int(input("Enter a decimal number: "))
print(f"Binary: {number:b}")

Both produce 11001 for input 25. The format() version is slightly more explicit; the f-string version is more idiomatic in Python 3.6 and later. Either is acceptable in a placement test.

Zero-padding to a fixed width is built in: format(25, '08b') produces 00011001, an 8-bit representation with leading zeros. This comes up in questions about byte-aligned binary output or fixed-length fields.

Comparing the three methods

Featurebin()Division loopformat() / f-string
Built-in dependencyYesNoYes
Output prefix0b (strip with [2:])NoneNone
Negative number handlingAdds minus signNeeds extra handlingAdds minus sign
Zero-padding supportNeeds zfill()Needs extra logicBuilt in with format spec
Placement use caseQuick conversionManual-implementation questionsFormatted output questions

For Python basic programs practice, bin() covers most needs. When a placement test explicitly asks to implement conversion without library functions, the division loop is the expected answer.

Binary conversion in placement coding rounds

The digit-extraction loop in the division-by-2 algorithm is the same building block used in Armstrong number checks: pull each digit from a number using modulo and integer division, then do something with it. Mastering this pattern once covers a class of problems that recurs in TCS NQT, Infosys Hackwithinfy, and Wipro National Talent Hunt coding rounds.

A practical note on how questions are phrased: TCS NQT and similar tests sometimes specify “implement without using Python’s built-in conversion functions.” That phrase targets bin(), format(), and int(n, 2). The division loop and the recursive version are both safe answers.

The relationship between the three methods also matters for debugging. If you write the division loop and get a wrong answer, verify the step that collects remainders (num % 2) and the step that advances the loop (num = num // 2): those are the two places errors appear. bin() and format() are correct by definition; if output differs from expected, the issue is usually the prefix or the sign, not the conversion.

If you are building on this topic with a calculator program in Python, bitwise operators like AND (&), OR (|), XOR (^), and the shift operators (>>, <<) all operate on the binary representation that bin() displays. Understanding how decimal maps to binary is the prerequisite for reading bitwise operation results correctly.

The three methods above produce identical bit strings, but the division-by-2 loop is the only one that builds a mental model you can extend. The same modulo-and-integer-division pattern drives palindrome checks, digit-sum algorithms, and the quantisation logic that makes LLM inference run on constrained hardware. TinkerLLM covers the Python path from these foundations toward applied LLM work, starting at ₹299.

Primary sources

Frequently asked questions

What does the 0b prefix mean in bin() output?

The '0b' prefix is Python's literal notation for binary numbers, telling Python and the reader that the digits that follow are base-2. Strip it with bin(n)[2:] for a plain binary string with no prefix.

How do I convert binary back to decimal in Python?

Use int() with a base argument: int('11001', 2) returns 25. You can also pass the '0b' prefix directly — int('0b11001', 2) works too. The second argument tells int() which base to parse.

What is the binary of 0 in Python?

bin(0) returns '0b0', so the plain binary string is '0'. The division-by-2 loop never executes when the input is 0, leaving an empty list — add an explicit check for n == 0 to return '0' directly.

Which decimal to binary method should I use in a placement test?

Use bin() for speed and readability when built-in functions are allowed. If the question asks for a manual implementation, use the division-by-2 loop — it is the standard algorithm question that tests number-system understanding.

Can Python's bin() function handle negative numbers?

Yes. bin(-5) returns '-0b101'. The negative sign appears before the '0b' prefix. For two's complement representation, apply a bitmask: bin(-5 & 0xFF) gives an 8-bit representation.

Is there a difference between format() and f-strings for binary conversion?

Both produce the same result. format(n, 'b') and the f-string f'{n:b}' call the same underlying formatting protocol. Use whichever fits the readability style of your surrounding code.

Build AI projects

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)
Free AI Roadmap PDF