How to use Python to convert an octal to a decimal

廉价感情. 提交于 2019-12-05 04:57:34

From decimal to octal:

oct(42) # '052'

Octal to decimal

int('052', 8) # 42

Depending if you want to return octal as a string or integer you might want to wrap it in str or int respectively.

Someone might find these useful

These first lines take any decimal number and convert it to any desired number base

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)

The second lines do the same but for a given range and a given decimal

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)

The third lines convert from any base back to decimal

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)

Note: I also have the GUI version if anyone needs them

def decimal_to_octal(num1):
  new_list = []
  while num1 >= 1:
    num1 = num1/8
    splited = str(num1).split('.')
    num1 = int(splited[0])
    appendednum = float('0.'+splited[1])*8
    new_list.append(int(appendednum))
    decimal_to_octal(num1)    
  return "your number in octal: "+''.join(str(v) for v in new_list[::-1])

print(decimal_to_octal(384))
def decimalToOctal(num1):
  new_list = []
  while num1 >= 1:
    num1 = num1/8
    splited = str(num1).split('.')
    num1 = int(splited[0])
    appendednum = float('0.'+splited[1])*8
    new_list.append(int(appendednum))
    decimalToOctal(num1)    
  return "your number in octal: "+''.join(str(v) for v in new_list[::-1])

print(decimalToOctal(384))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!