How to use Python to convert an octal to a decimal

34,422

From decimal to octal:

oct(42) # '052'

Octal to decimal

int('052', 8) # 42

If you want to return octal as a string then you might want to wrap it in str.

Share:
34,422
Austin Wildgrube
Author by

Austin Wildgrube

Updated on March 26, 2021

Comments

  • Austin Wildgrube
    Austin Wildgrube about 3 years

    I had this little homework assignment and I needed to convert decimal to octal and then octal to decimal. I did the first part and could not figure out the second to save my life. The first part went like this:

    decimal = int(input("Enter a decimal integer greater than 0: "))
    
    print("Quotient Remainder Octal")
    bstring = " "
    while decimal > 0:
        remainder = decimal % 8
        decimal = decimal // 8
        bstring = str(remainder) + bstring
        print ("%5d%8d%12s" % (decimal, remainder, bstring))
    print("The octal representation is", bstring)
    

    I read how to convert it here: Octal to Decimal, but I have no clue how to turn it into code.

  • Jacob
    Jacob over 5 years
    An explanation along with the answer would be useful.
  • Admin
    Admin over 5 years
    take into account ))
  • joce
    joce over 5 years
    Adding some comments as to why this answers the original poster's question would be welcome.
  • Peter Mortensen
    Peter Mortensen about 3 years
    It is identical to your previous answer.
  • Peter Mortensen
    Peter Mortensen about 3 years
    An explanation would be in order.