convert a number from base 10 to base 8 in python

To convert a number from base 10 to base 8 in Python, we can use the built-in oct() function. oct() takes an integer as input and returns its octal representation as a string.

main.py
decimal_number = 23
octal_number = oct(decimal_number)
print(octal_number)  # Output: '0o27'
93 chars
4 lines

The output is a string starting with '0o', indicating that it is an octal number. We can use string slicing to remove the '0o' prefix if desired.

If we want to implement the conversion ourselves, we can use the repeated division method. Here's an example implementation:

main.py
def decimal_to_octal(decimal_num):
    quotient = decimal_num
    octal_num = ''
    
    while quotient > 0:
        remainder = quotient % 8
        octal_digit = str(remainder)
        octal_num = octal_digit + octal_num
        quotient = quotient // 8
    
    return octal_num
    
decimal_number = 23
octal_number = decimal_to_octal(decimal_number)
print(octal_number)  # Output: '27'
392 chars
16 lines

Here, we repeatedly divide the decimal number by 8 and take remainders until the quotient is zero. The remainders make up the octal digits, which are added to the beginning of the octal_num string. Finally, the octal_num string is returned as the octal representation of the decimal number.

gistlibby LogSnag