将十进制转换为十六进制-如何使其更短?

时间:2019-09-26 21:32:42

标签: python int hex

我编写了一个代码,该代码应将整数转换为十六进制。这是学校的作业。我写了很多,后来我的一个朋友给我看了他的代码,代码要短得多,这就是为什么我想知道我在哪里使事情变得过于复杂,以及在哪里可以切除。 附带说明,我已经学习了2个月了,所以请放心:)!

我检查了我的代码,但是找不到任何可以删除或简化的东西。

       def Exponent2():                    # which exponent I need to 
                                                           devide with
       global Exponent
       Exponent = 0
       while True:
             a = dezimal // 16**Exponent
             Exponent = Exponent + 1
             if a == 0:
             Exponent = Exponent - 1
             break

        Exponent2()
        Ergebnis = ''
        Dezimal2 = dezimal
        while Dezimal2 != 0:
            dezimal = Dezimal2 // 16**Exponent
            Dezimal2 = Dezimal2 % 16**Exponent
            CheckReverse()
            Ergebnis = Ergebnis + str(dezimal)
            Exponent = Exponent - 1

        Länge = len(Ergebnis)
        Ergebnis = Ergebnis[1:Länge]
        print(Ergebnis)

1 个答案:

答案 0 :(得分:0)

看起来您找到了最大的指数x,可以在其中将数字除以16**x。相反,您可以从可以除以的最小指数开始。换句话说,如果只除以16,则得到一个数字,然后再除以16,得到下一个十六进制数字。