如何使用Python将八进制转换为十进制

2024-05-23 16:09:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小作业,我需要把十进制转换成八进制,然后八进制转换成十进制。我做了第一部分,却想不出第二部分来挽救我的生命。第一部分是这样的:

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)

我在这里读过如何转换它:Octal to Decimal,但不知道如何将它转换成代码。如有任何帮助,我们将不胜感激。谢谢您。


Tags: input作业integerint八进制decimalprintenter
3条回答

也许有人会觉得这些有用

这些第一行接受任何十进制数并将其转换为任何所需的基数

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版本

从十进制到八进制:

oct(42) # '052'

八进制到十进制

int('052', 8) # 42

如果您想以字符串形式返回八进制,那么您可能需要将它包装成str

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))

相关问题 更多 >