有没有一种方法可以使此代码减少计算机负担?

时间:2020-06-02 18:48:15

标签: python compiler-errors

我有一些Python可以将十进制数转换为十六进制,但是,我的计算机会永久占用并在代码完成之前关闭。有没有办法将此代码压缩为更少的行?我已经下载了Python 3.8.3。 python是纯文本文件(但 .py ),我正在通过macOS High Sierra(v10.13.6)上的终端运行它。

import math

dec = float(input("Decimal: "))

while(math.floor(dec/16) >= 0):
  x = "Hex: "
  rem = dec/16 - math.floor(dec/16)
  myHex = rem*16
  if myHex > 9 :
    if myHex == 10 :
      x += "A"

    if myHex == 11 :
      x += "B"

    if myHex == 12 :
      x += "C"

    if myHex == 13 :
      x += "D"

    if myHex == 14 :
      x += "E"

    if myHex == 15 :
      x += "F"

  else :
    x += str(myHex)  

print (x)

1 个答案:

答案 0 :(得分:0)

您可以只使用struct模块:

import struct

f = float(input("> "))
print(hex(struct.unpack('<I', struct.pack('<f', f))[0]))

输入:

> 234.345

输出:

0x436a5852
相关问题