-1

I have some python to convert a Decimal number into a Hexadecimal, however, my computer takes forever and shuts off before the code even finishes. Is there a way to compact this code to less lines? I have Python 3.8.3 downloaded. The python is in a plain text (but .py) file and I am running it through terminal on 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)
RedSox2
  • 7
  • 8

1 Answers1

0

You can just use the struct module:

import struct

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

Input:

> 234.345

Output:

0x436a5852
Red
  • 26,798
  • 7
  • 36
  • 58