How to use Python to convert octal to decimal

I have this little homework and I needed to convert the decimal code to octal and then octal to decimal. I did the first part and I can not understand the second in order to save my life. The first part was as follows:

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 have no idea how to turn it into code. Any help is appreciated. Thanks.

+4
source share
3 answers

Decimal to octal:

oct(42) # '052'

Axis to decimal

int('052', 8) # 42

, , str int .

+11

-

def dec2base():
a= int(input('Enter decimal number: \t'))
d= int(input('Enter expected base: \t'))
b = ""
while a != 0:
    x = '0123456789ABCDEF'
    c = a % d
    c1 = x[c]
    b = str(c1) + b
    a = int(a // d)
return (b)

,

def dec2base_R():
a= int(input('Enter start decimal number:\t'))
e= int(input('Enter end decimal number:\t'))
d= int(input('Enter expected base:\t'))
for i in range (a, e):
    b = ""
    while i != 0:
        x = '0123456789ABCDEF'
        c = i % d
        c1 = x[c]
        b = str(c1) + b
        i = int(i // d)
    return (b)

def todec():
c = int(input('Enter base of the number to convert to decimal:\t')) 
a = (input('Then enter the number:\t ')).upper()
b = list(a)
s = 0
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
for pos, digit in enumerate(b[-1::-1]):
    y = x.index(digit)
    if int(y)/c >= 1:
            print('Invalid input!!!')
            break
    s =  (int(y) * (c**pos)) + s
return (s)

. GUI, - .

0

.

Decimal to Octal

def decimal_to_octal(number):
    i = 1
    octal = 0
    while (number != 0):
        reminder = number % 8
        number /= 8
        octal += reminder * i
        i *= 10
    return octal
>> print decimal_to_octal(100)
>> 144


def octal_to_decimal(number):
    i = 1
    decimal = 0
    while (number != 0):
        reminder = number % 10
        number /= 10
        decimal += reminder * i
        i *= 8
    return decimal
>> print octal_to_decimal(100)
>> 64
-1

Source: https://habr.com/ru/post/1526822/


All Articles