Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python to convert an octal to a decimal

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.

like image 200
Austin Wildgrube Avatar asked Feb 17 '16 07:02

Austin Wildgrube


People also ask

How do you convert decimal to octal in Python?

Source Code. # Python program to convert decimal into other number systems dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.") The decimal value of 344 is: 0b101011000 in binary.

How do you convert 275 octal to decimal?

Convert Octal to Decimal Worked Examples So 275 in octal is equal to 189.

How do you convert 0.75 to octal?

Conversions of Decimal Fractions to Octal Fractions – The conversion of decimal fraction to octal fraction is similar to decimal fraction to binary fraction. Here we multiply the fraction by 8 instead of 2. Example – Find the octal equivalent of (0.75)10. Number (to be recorded) 0.75 x 8 = 6.00 Thus (0.75)10 = (0.6)8.

How do I print an octal number without 0o in Python?

Method 1: Slicing To skip the prefix, use slicing and start with index 2 on the octal string. For example, to skip the prefix '0o' on the result of x = oct(42) ='0o52' , use the slicing operation x[2:] that results in just the octal number '52' without the prefix '0o' .


1 Answers

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.

like image 107
martin Avatar answered Sep 18 '22 05:09

martin