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:
JavaScript
x
11
11
1
decimal = int(input("Enter a decimal integer greater than 0: "))
2
3
print("Quotient Remainder Octal")
4
bstring = " "
5
while decimal > 0:
6
remainder = decimal % 8
7
decimal = decimal // 8
8
bstring = str(remainder) + bstring
9
print ("%5d%8d%12s" % (decimal, remainder, bstring))
10
print("The octal representation is", bstring)
11
I read how to convert it here: Octal to Decimal, but I have no clue how to turn it into code.
Advertisement
Answer
From decimal to octal:
JavaScript
1
2
1
oct(42) # '052'
2
Octal to decimal
JavaScript
1
2
1
int('052', 8) # 42
2
If you want to return octal as a string then you might want to wrap it in str
.