gpt4 book ai didi

Python程序解释: Decimal to hex

转载 作者:行者123 更新时间:2023-12-01 05:16:43 24 4
gpt4 key购买 nike

有人可以向我解释一下这是如何工作的吗?我一直看着它,但我就是不明白。它似乎工作得很好,但对我来说这毫无意义。请有人帮忙。

# Convert a decimal to a hex as a string 
def decimalToHex(decimalValue):
hex = ""

while decimalValue != 0:
hexValue = decimalValue % 16
hex = toHexChar(hexValue) + hex
decimalValue = decimalValue // 16

return hex

# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else: # 10 <= hexValue <= 15
return chr(hexValue - 10 + ord('A'))

def main():
# Prompt the user to enter a decimal integer
decimalValue = eval(input("Enter a decimal number: "))

print("The hex number for decimal",
decimalValue, "is", decimalToHex(decimalValue))

main() # Call the main function

最佳答案

打印字符

好吧,我会尝试解释一下。首先,让我们看看将数字从 0-15 转换为 0123...ABCDEF 的函数:

def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else: # 10 <= hexValue <= 15
return chr(hexValue - 10 + ord('A'))

可以看到,它处理两种情况:一种是数字0-9需要转换成'0'到'9'的文本字符,另一种是数字10-16需要转换成从“A”到“F”的文本字符。它将根据字符的 ASCII 代码返回字符。例如,ord('A') 返回 65。chr() 会将整数从 65 转换回 ascii 字符“A”。

这就是打印功能。现在循环:

迭代数字,直到生成所有十六进制字符

当十进制值!= 0:

此循环将一直运行,直到无法获取 16er block 为止

十六进制值 = 小数值 % 16

正常模数。它从小数中提取一个 block (hexValue 将为 0-15)

十六进制 = toHexChar(hexValue) + 十六进制

构建一个字符串。由于十六进制被标准化为在左侧有更大的数字部分,因此它会预先考虑转换后的字符。

decimalValue =decimalValue//16

准备下一个循环:使用 floordiv(a, b) 删除这个 16er block (写为//b)。

示例

让我们了解它是如何工作的。假设我们想要将数字 255 转换为 HexString。它将首先调用模 255 % 16 = 15。然后它将被转换为 toHexChar(15) = 'F'

下一步是删除该 16er block 。如果我们使用普通除法,我们会得到255/16 = 15.9375。然而,这将被四舍五入,因为它在小数点后高于 0.5 导致错误的行为(结果将是 0x1FF)。这就是为什么我们必须使用一个 Floordivsion ,它是floor(255/16) = 15 或简称:255//16 = 15

我希望这能更好地解释它,特别是为什么需要//。

关于Python程序解释: Decimal to hex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23046232/

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