Python将decimal转换为hex [英] Python convert decimal to hex
本文介绍了Python将decimal转换为hex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数将小数转换为十六进制,但它以相反的顺序打印出来。如何修复它?
I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
if (x == 11):
print("B"),
if (x == 12):
print("C"),
if (x == 13):
print("D"),
if (x == 14):
print("E"),
if (x == 15):
print ("F"),
ChangeHex( n / 16 )
推荐答案
如果您想自己编写代码而不是使用内置函数 hex()
,则可以在打印当前数字之前简单地执行递归调用:
If you want to code this yourself instead of using the built-in function hex()
, you can simply do the recursive call before you print the current digit:
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print n,
else:
ChangeHex( n / 16 )
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
if (x == 11):
print("B"),
if (x == 12):
print("C"),
if (x == 13):
print("D"),
if (x == 14):
print("E"),
if (x == 15):
print ("F"),
这篇关于Python将decimal转换为hex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文