gpt4 book ai didi

python - 有没有办法让这段代码在计算机上的负担更少?

转载 作者:行者123 更新时间:2023-12-02 11:09:54 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Python convert decimal to hex

(24 个回答)


1年前关闭。




我有一些 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)

最佳答案

您可以使用 struct模块:

import struct

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

输入:
> 234.345

输出:
0x436a5852

关于python - 有没有办法让这段代码在计算机上的负担更少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62159231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com