Convert Decimal to Octal in Python

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Base conversion

What you’ll learn

  • How division by eight and remainders produce octal digits 0 to 7.
  • Why you must handle zero separately and reverse collected digits.
  • A recursive MSB-first approach, plus a live preview.

Overview

Octal is base 8. For a nonnegative decimal number n, repeatedly take n % 8 and then reduce with n // 8. The collected digits are read in reverse to form octal.

Two programs

Classic remainder collection and recursive MSB-first output.

Live preview

Quickly test safe nonnegative inputs in the browser.

Binary link

Each octal digit equals exactly three binary bits.

Prerequisites

Loops, modulo, integer division, lists, and optional recursion.

  • Use // and % correctly on integers.
  • Join and reverse list elements to print from MSB to LSB.

Decimal to octal

In octal, each digit place is a power of 8. The operation n % 8 gives the rightmost octal digit of n.

Example: 57 = 7 * 8 + 1, so octal form is 71.

Decimalbase 10
Octalbase 8
Digits0 to 7

Division algorithm

For n >= 0, repeatedly compute quotient and remainder under division by 8. The remainder sequence, read backwards, is the octal representation.

57

57 -> 7 r1, then 7 -> 0 r7. Reverse remainders 1,7 to get 71.

Intuition

64100₈
Power
8^2
5771₈
Split
7*8 + 1

Takeaway: each step peels one octal digit from the right.

Live preview

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

Negative values are not supported in this widget.

Live result
Press “Show octal” to convert.

Algorithm (remainder method)

Goal: print octal digits of nonnegative n in normal left-to-right order.

Handle zero

If n == 0, output 0.

Collect digits

While n > 0, append n % 8 and set n //= 8.

Reverse and join

Reverse collected digits and combine into one string.

📜 Pseudocode

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)
1

Divide by eight and reverse

Simple and beginner-friendly approach using a list of remainders.

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))

Explanation

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

2

Recursive MSB-first print

No explicit reversal list: recursion prints higher digits first.

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))

Explanation

The call stack naturally delays lower digits until higher digits are printed.

Optimization and built-ins

Use built-ins. format(n, "o") gives octal digits directly for nonnegative n.

Binary grouping. Group binary bits in 3s to convert quickly between binary and octal.

Interview tip: explain manual algorithm first, then mention built-in shortcuts.

❓ FAQ

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).

🔄 Input / output examples

Try these values with either method.

DecimalOctal
00
77
810
5771
64100

Edge cases and pitfalls

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.

Recursion

Deep calls

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

⏱️ 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.

Summary

  • Idea: repeatedly take % 8 and divide by 8.
  • Code: handle zero explicitly, then reverse collected digits.
  • Bonus: one octal digit equals three binary bits.
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.

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.

8 people found this page helpful