我编写了一个将Decimal转换为十六进制的程序,它相当于python中的hex()函数。程序打印正确的值直到'2559'。如何为较大的数字获取十六进制的正确值。代码无法从2600十进制值给出正确的十六进制表示。这是我的代码:
#########################################
#Decimal to Hexadecimal Conversion #
#########################################
def DectoHex(n):
if n <= 16:
return n
elif n>16:
if n%16 == 10:
x = 'A'
elif n%16 == 11:
x = 'B'
elif n%16 == 12:
x = 'C'
elif n%16 == 13:
x = 'D'
elif n%16 == 14:
x ='E'
elif n%16 == 15:
x = 'F'
else:
x = n%16
print x
n = n/16
print n
if n == 10:
n = 'A'
elif n == 11:
n = 'B'
elif n == 12:
n = 'C'
elif n == 13:
n = 'D'
elif n == 14:
n ='E'
elif n == 15:
n = 'F'
elif n>=16:
if n%16 == 10:
n = str(n/16) + 'A'
elif n%16 == 11:
n = str(n/16) + 'B'
elif n%16 == 12:
n = str(n/16) + 'C'
elif n%16 == 13:
n = str(n/16) + 'D'
elif n%16 == 14:
n = str(n/16) + 'E'
elif n%16 == 15:
n = str(n/16) + 'F'
else:
n = str(n/16) + str(n%16)
print n
return str(n) + str(x)
print "Would you like to continue:"
print "Enter 'Y' to continue, 'N' to quit"
Str = str (raw_input("> "))
while True:
if Str == 'Y':
print "Enter a decimal number:"
dec = int (raw_input("> "))
Hex = DectoHex(dec)
print "The number in base 16 is:", Hex
print "Enter 'Y' to continue, 'N' to quit"
Str = str (raw_input("> "))
elif Str == 'N':
print "Good Bye!"
break
else:
print "Plesae Enter 'Y' or 'N'"
Str = str (raw_input("> "))
答案 0 :(得分:0)
如果您编写的代码不仅仅是一个实验,那么您应该使用Python的hex()(docs.python.org/library/functions.html#hex)。话虽这么说,我会帮你修复你自己的实现。
您正在使用案例来处理将十进制转换为基数为16的字符,并且您这样做的次数有限,这就解释了为什么您的代码达到了极限。我建议在一个单独的函数中定义十进制到十六进制的转换,如下所示:
def toHex(n):
if n % 16 == 10:
x = 'A'
elif n % 16 == 11:
x = 'B'
elif n % 16 == 12:
x = 'C'
elif n % 16 == 13:
x = 'D'
elif n % 16 == 14:
x = 'E'
elif n % 16 == 15:
x = 'F'
else:
x = n % 16
return x
请注意,n%16可能已存储在临时变量中。
执行相同操作的一个更短的方法是根据索引直接从字符串中抓取字符:
DEC_TO_HEX_SINGLE_DIGIT = "0123456789ABCDEF"
def toHex(n): # 0 < n < 16
return DEC_TO_HEX_SINGLE_DIGIT[n]
在DectoHex函数中,您将在有限次数上添加十六进制数字。您应该使用递归或循环来构建十六进制字符串。递归示例如下:
def DectoHex(n):
if n < 16:
return toHex(n)
mod = n % 16
n /= 16
return DectoHex(n) + str(toHex(mod))
答案 1 :(得分:-1)