Python oct(): Convert Numbers to Octal

The oct() function converts an integer into an octal (base 8) string. It’s useful for working with low-level data, file permissions, and optimizing memory representation.

Example

num = 64
print(oct(num))  
# Output: '0o100'

The prefix 0o indicates an octal number.

Syntax

oct(number)
  • number → An integer to convert to octal.
  • Returns → A string starting with '0o', representing an octal number.

1. Converting Numbers to Octal

print(oct(8))     # Output: '0o10'
print(oct(16))    # Output: '0o20'
print(oct(255))   # Output: '0o377'

Each decimal number gets its octal equivalent.

2. Removing the ‘0o‘ Prefix

num = 64
print(format(num, "o"))  
# Output: '100'

Useful when you only need the digits.

3. Converting Octal Back to Integer

Use int() to convert an octal string back to decimal.

print(int("0o100", 8))  
# Output: 64

This works for any valid octal string.

4. Using Octal in File Permissions (Linux)

Octal is commonly used for Unix file permissions.

permissions = 0o755
print(permissions)  
# Output: 493 (decimal)

0o755 is a standard executable permission in Unix systems.

5. Handling Negative Numbers

print(oct(-42))  
# Output: '-0o52'

Negative numbers keep the minus sign.

Key Notes

  • Converts integers to octal format.
  • Useful for file permissions, bitwise operations, and memory optimization.
  • Prefix 0o indicates octal numbers.
  • Use format(num, "o") to remove the prefix.

By using oct(), you can handle octal numbers efficiently, making it essential for systems programming and file management. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top