Convert Decimal to Octal in Python

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Base conversion

What You’ll Learn

Decimal-to-octal conversion turns a base-10 integer into a base-8 digit string (digits 0–7). This tutorial covers remainders, recursion, built-ins, a live preview, worked Python examples, edge cases, and complexity.

Powers of Eight

Base 8

Each digit is a coefficient on 1, 8, 64, 512…

Remainders

n % 8

Collect digits LSD-first, then reverse for MSD-first output.

Recursion

MSB first

Recurse on n // 8 before appending n % 8 — no reverse list.

Handle Zero

Special case

Return "0" — a plain while n > 0 loop would print nothing.

Binary Link

3 bits each

One octal digit equals exactly three binary bits.

O(log n)

Complexity

About log8 n digits for nonnegative n.

Introduction

Decimal-to-octal conversion writes a nonnegative integer using digits 0–7 only. Classic example: 57 = 7 × 8 + 1 → octal 71.

The classroom method divides by 8 and stacks remainders (LSD first), then reverses. Recursion or format(n, "o") can produce the same string more directly.

Why it matters?

It generalizes the binary conversion pattern, trains base-8 place value, and links neatly to binary triplets.

Key Highlights

LSD First

First remainder is the rightmost digit.

Reverse to Print

MSD-first output needs a reverse (or recursion).

Zero Guard

Always return "0" for input 0.

3 Binary Bits

Each octal digit packs three bits.

In short: repeatedly take n % 8 and n //= 8, reverse the digits (or recurse MSD-first), and special-case zero.

📝 Problem & Approach

Given a nonnegative integer n, return its octal representation as a string (minimal digits, no leading zeros except for 0).

python
# 57 → remainders 1, 7 → reverse → "71"
# 64 → "100"
# 0  → "0"

Inputs & Outputs

ItemTypeDescription
nintNonnegative integer (define policy for negatives).
Return / printstrOctal digits as a string, e.g. "71".

Minimal workflow

Pseudocode
function decimal_to_octal(n):  // n >= 0
    if n == 0:
        return "0"
    digits = []
    while n > 0:
        digits.append(n mod 8)
        n = floor(n / 8)
    reverse(digits)
    return join(digits)

Method comparison

MethodIdeaNotes
Remainder + reverseCollect n % 8, then reverseBest classroom / interview explanation
Recursive MSD-firstRecurse on n // 8, then append n % 8No reverse list
Built-informat(n, "o") / oct(n)[2:]Idiomatic production Python

⚡ Quick Reference

GoalPattern
Next digitn % 8
Drop digitn //= 8
MSD-first outputdigits.reverse() or recurse first
Zero caseif n == 0: return "0"
Built-informat(n, "o")
Binary grouping3 bits ↔ 1 octal digit

📋 Remainder vs Recursion vs Built-in

Same octal string — different clarity and interview signaling.

Remainder
% 8 + reverse

Shows place-value / division clearly

Recursion
MSD first

Call stack delays lower digits naturally

Built-in
format / oct

Shortest production style

Interview tip
remainders first

Explain loops, then mention built-ins

Context

When This Problem Shows Up

Reach for decimal-to-octal drills when base-8 conversion and binary grouping matter.

  1. Interview warm-ups

    Same remainder pattern as binary, with digits 0–7.

  2. Teaching binary triplets

    Octal is a compact way to read binary in groups of three.

  3. Unix / permission lore

    Classic chmod modes are often written in octal.

  4. Gateway to hex

    Same idea with base 16 and digit alphabet 0–9A–F.

  5. Not for floats alone

    Fractional octal needs a different place-value story after the point.

Key benefit: one short problem that generalizes binary conversion and connects neatly to 3-bit grouping.

🔮 Live Preview

Nonnegative integers in JavaScript safe range, using toString(8).

Try 0, 8, 57, or 64. Negatives are not supported in this widget.

Live result
Press “Show octal” to convert.

Examples Gallery

Three complete Python programs — remainder + reverse, recursive MSD-first, and built-in formatting. Click View Output to reveal sample console results.

📚 Getting Started

Classic divide-by-eight approach — collect, then reverse.

Example 1 — Divide by Eight and Reverse

Collect remainder digits LSD-first, then reverse to print MSD-first.

python
def decimal_to_octal(n: int) -> str:
    if n == 0:
        return "0"

    digits: list[str] = []
    while n > 0:
        digits.append(str(n % 8))
        n //= 8

    digits.reverse()
    return "".join(digits)


print("Octal equivalent:", decimal_to_octal(57))
print("Octal equivalent:", decimal_to_octal(0))

How It Works

Remainders come from right to left, so reversing is required for proper left-to-right octal display.

⚡ Recursive Style

No explicit reversal list — the call stack prints higher digits first.

Example 2 — Recursive MSD-First Print

Recurse on n // 8, then append n % 8.

python
def print_octal_recursive(n: int) -> str:
    if n < 8:
        return str(n)
    return print_octal_recursive(n // 8) + str(n % 8)


print("57 in octal:", print_octal_recursive(57))
print("0 in octal:", print_octal_recursive(0))

How It Works

The call stack naturally delays lower digits until higher digits are printed — base case n < 8 returns a single digit (including 0).

🚀 Idiomatic Python

Same answer with built-ins — great after you know the algorithm.

Example 3 — Using format / oct

Minimal digits, plus a quick binary-triplet check.

python
def to_octal_builtin(n: int) -> str:
    if n < 0:
        raise ValueError("This helper expects a nonnegative integer")
    return format(n, "o")


print(to_octal_builtin(57))
print(to_octal_builtin(0))
print(oct(57)[2:])          # strip the '0o' prefix
print(format(57, "b"))      # binary of 57
# 71 octal ↔ 111 001 binary (7=111, 1=001)

How It Works

format(n, "o") is the cleanest minimal-digit conversion. Grouping binary 111001 as 111 001 recovers octal digits 7 and 1.

🧠 How the Algorithm Converts

1

Handle zero

If n == 0, return "0" immediately.

Guard
2

Collect digits

Append n % 8, then n //= 8 until n becomes 0.

Loop
3

Reverse / join

Reverse the list (or have recursed MSD-first) and join into a string.

Format
=

Octal string

Return the MSD-first digit string — that is the base-8 form of n.

🔎 Worked Walkthrough — n = 57

Trace the remainder method. Digits collect LSD-first, then reverse.

nn % 8n // 8digits so far
5717[1]
770[1, 7]

Reverse → 71. Check: 7 × 8 + 1 = 57.

Use Cases

Where decimal-to-octal conversion shows up beyond the interview prompt.

1. Interview Warm-Ups

Generalizes binary conversion to another base.

Example: write decimal_to_octal(n).

2. Teaching Binary Groups

Map each octal digit to three bits.

Example: 7 ↔ 111.

3. File Permission Modes

Unix modes are often written in octal.

Example: 755, 644.

4. Gateway to Hex

Same remainder idea with base 16.

Example: n % 16 + digit map.

5. Round-Trip Practice

Convert to octal then back with int(s, 8).

Example: assert int(octal, 8) == n.

6. Recursion Practice

MSD-first print is a clean recursion demo.

Example: recurse then append remainder.

Pro Tip: say “first remainder is the LSD” before coding — same tip as for binary, with base 8.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Familiar Pattern

    Same structure as decimal-to-binary — only the divisor changes.

  2. 2. Binary Shortcut

    Three-bit groups make mental conversion fast.

  3. 3. Easy Built-in

    format(n, "o") keeps application code short after the theory.

  4. 4. Clear Complexity

    O(log8 n) digits are easy to argue in interviews.

Pro Tip: after binary, ask yourself “what changes for octal?” — answer: divisor 8 and digit range 0–7.

Usage Tips

Small habits that keep decimal-to-octal solutions interview-ready.

  1. 1. Special-Case Zero

    Return "0" before the remainder loop.

  2. 2. Say LSD First Out Loud

    Then reverse (or recurse) for MSD-first print.

  3. 3. Spot-Check 57 and 8

    Expect 71 and 10 as golden tests.

  4. 4. Mention Binary Triplets

    Shows you understand why octal exists historically.

  5. 5. Mention Built-ins Second

    Show the loop first; then format(n, "o").

Pro Tip: round-trip with int(octal, 8) to catch reverse mistakes instantly.

Common Pitfalls

Mistakes that commonly break decimal-to-octal solutions.

  1. 1. Forgetting to Reverse

    Printing remainders in collection order reverses the digits.

    → Reverse the list (or recurse MSD-first).

  2. 2. Empty Output for Zero

    while n > 0 never runs when n is 0.

    → Return "0" explicitly.

  3. 3. Dividing by 10 by Habit

    Copying a decimal digit-extraction loop is a common slip.

    → Use % 8 and // 8.

  4. 4. Leaving the 0o Prefix

    oct(n) returns 0o... which often fails string checks.

    → Use oct(n)[2:] or format(n, "o").

  5. 5. Deep Recursion on Huge n

    Very large integers can hit recursion limits.

    → Prefer the iterative remainder method for huge values.

Edge Cases

Set rules for negative numbers early; many beginner versions accept only nonnegative input.

Zero

n == 0

Without explicit handling, loop-based code can return empty output.

Negative

Choose policy

Either reject negatives or define representation convention clearly.

Digits

Only 0 to 7

Octal never uses digits 8 or 9.

Powers of 8

8, 64, 512

Become 10, 100, 1000 — good reverse checks.

Single digit

n in 1…7

Already octal — return unchanged as a string.

Recursion

Deep calls

For extremely large integers, iterative methods avoid recursion depth concerns.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Binary triplets. One octal digit = three binary bits (7 ↔ 111).
  • Uniqueness. Every nonnegative integer has a unique octal form without leading zeros (except 0).
  • Inverse. Octal-to-decimal uses place values or int(s, 8).
  • Digit count. Positive n needs about floor(log8 n) + 1 octal digits.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify classics

  • 0 → 0
  • 57 → 71
  • 64 → 100

2. Match all three styles

  • Remainder, recursive, format
  • Assert identical strings

3. Binary triplets

  • Convert 57 to binary
  • Group as 111 001 ↔ 71

4. Round-trip

  • Convert to octal then back
  • Use int(s, 8)

Notes

  • Idea: repeatedly take % 8 and divide by 8.
  • Code: handle zero explicitly, then reverse collected digits.
  • Bonus: one octal digit equals three binary bits.
  • State O(log8 n) time for nonnegative n.

Quick Takeaway: collect n % 8 remainders, reverse them (or recurse MSD-first), and special-case zero.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Remainder + reverse listO(log8 n)O(log8 n)
Recursive printO(log8 n)O(log8 n) stack
Built-in formatTypically O(d) digitsO(d) output

Here n is nonnegative and d is the number of octal digits.

Wrap Up

🎉 Conclusion

Decimal-to-octal conversion is the binary remainder pattern with divisor 8: collect digits LSD-first, reverse for MSD-first output, and handle zero. Recursion and format are strong follow-ups once the theory is clear.

Practice the three examples above, then continue to Disarium numbers for a digit-power warm-up.

Always special-case 0, remember the first remainder is the LSD, and mention the 3-bit binary link.

💡 Best Practices

✅ Do

  • Handle n == 0 first
  • Explain LSD-first remainders
  • Reverse (or recurse) for MSD output
  • Test 0, 57, and 64
  • Mention format/oct as a shortcut

❌ Don’t

  • Forget the reverse step
  • Return empty string for 0
  • Divide by 10 by accident
  • Leave negatives undefined
  • Ship oct(n) with the 0o prefix by accident

Key Takeaways

Knowledge Unlocked

Five things to remember about decimal to octal

Convert base 10 the interview-friendly way.

5
Core concepts
8 02

Base

Divide by 8

Math
0 03

Zero

Return "0"

Guard
3 04

Binary

3 bits each

Link
O 05

Complexity

O(log n)

Analysis

❓ Frequently Asked Questions

Octal is base 8. The remainder n % 8 gives the least significant octal digit, and n // 8 removes that digit for the next step.
Remainders are generated from least significant digit to most significant digit. Reversing prints the standard left-to-right octal form.
A plain while n > 0 loop does not run, so you must special-case 0 and return '0'.
Yes. oct(n) returns strings like '0o71'. If you want digits only, use format(n, 'o'). Learning the manual method still helps interviews.
One octal digit equals three binary bits. For example, octal 7 corresponds to binary 111.
For nonnegative n, remainder method uses O(log8 n) digits, which is O(log n).
Only 0 through 7. Digits 8 and 9 never appear in a valid octal string.
It prints higher digits first by recursing on n // 8 before appending n % 8, so no explicit reverse is needed.

Did you Know? 🔊

Each octal digit maps to exactly three binary bits. That is why octal is often taught as a quick way to compress binary.

Continue to Disarium Number

Learn how to check whether a number equals the sum of its digits raised to their positional powers.

Disarium number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful