gpt4 book ai didi

python - 数字系统转换器python

转载 作者:太空宇宙 更新时间:2023-11-04 09:44:44 25 4
gpt4 key购买 nike

您好,我想制作自己的数字转换器,将二进制、八进制或十六进制的输入转换为相应的十进制值。

我必须使用 2 个单独的函数,第一个将字母数字转换为数值,然后第二个通过使用输入基数将结果转换为十进制值...

   def hexConvert (x):
return int(x, base)

x = str(input("input value to convert to decimal: "))
base = int(input("Base of value to be converted to decimal: "))
print(x, " in base ", base, " = ", hexConvert(x), " in decimal")

我知道这很好用而且很稳健。我想通过手动操作来学习如何使用更多 Python 函数。

这是我目前拥有的:

    number = (input("Enter value to be converted to decimal: "))
base = int(input("Enter the base of the value: "))

for index in number:
print(index)
def hexConvert(number, base):
for number > 0:
if number == 1:
return 1
if number == 2:
return 2
if number == 3:
return 3
if number == 4:
return 4
if number == 5:
return 5
if number == 6:
return 6
if number == "7":
return 7
if number == "8":
return 8
if number == "9":
return 9
if number == "A":
return 10
if number == "B":
return 11
if number == "C":
return 12
if number == "D":
return 13
if number == "E":
return 14
elif number == "F":
return 15
else:
print(number)


nString = ""
def deciConvert(number, base):
number = int(number)
while number > 0:
bString = number%base
nString = nString + str(bString)
number = number // base

print(deciConvert(number, base))

此时我迷失了自己,我想我还没有开始任何计算,我真的很感激任何第二意见。谢谢你!

最佳答案

我会推荐通用的 encodedec_to_base 函数

ALPHABET = \
"0123456789abcdefghijklmnopqrstuvwxyz"

def encode (n):
try:
return ALPHABET [n]
except IndexError:
raise Exception ("cannot encode: %s" % n)

def dec_to_base (dec = 0, base = 16):
if dec < base:
return encode (dec)
else:
return dec_to_base (dec // base, base) + encode (dec % base)

print (dec_to_base (9))
# 9

print (dec_to_base (10))
# a

print (dec_to_base (255))
# ff

print (dec_to_base (256))
# 100

当然它可以与其他基地一起使用

print (dec_to_base (255, base = 2))
# 11111111

print (dec_to_base (256, base = 2))
# 100000000

反转编码是通过提供同构decodebase_to_dec

def decode (s):
try:
return ALPHABET.index(s)
except ValueError:
raise Exception ("cannot decode: %s" % s)

def base_to_dec (s, base = 16, pow = 0):
if s is "":
return 0
else:
return decode (s[-1]) * (base ** pow) + base_to_dec (s[0:-1], base, pow + 1)

print (base_to_dec ('ff'))
# 255

print (base_to_dec ('100'))
# 256

并使用不同的基础

print (dec_to_base ('11111111', base = 2))
# 255

print (dec_to_base ('100000000', base = 2))
# 256

关于python - 数字系统转换器python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com