将小数转换为十六进制(不带'hex()`函数)

时间:2018-02-20 20:42:55

标签: python hex

在我开始任何事情之前,我只想说我知道  hex()功能,对于这个项目,我无法使用它。另外,对于提出的问题here,我已经意识到这一点,并且我已经尝试过该解决方案,但无法使我的代码正常工作。我正在使用多种功能,这是一种不同的情况。那个帖子也没有讨论我的第二个问题。

我有两个问题:

  1. 到目前为止我的代码可以将小数转换为十六进制。我遇到的问题是,当我打印十六进制时,它会向后打印。
  2. 我想要输出:
  3.   

    输入小数值:589
      589等于十六进制的24D

    但是当我有这条线时:

    print(og_dec_value,"is equal to",getHexChar(hex_value),end="","in hexadecimal")

    我收到关于end=""没有结束的错误。但是,如果我删除end="",那么它只打印出十六进制的第一个数字而不会丢弃其余部分。

    这是我现在的代码:

    def main():
        decToHex(int(input("Enter decimal value: ")))
    
    def decToHex(dec_value):
        while dec_value > 0:
            hex_value=dec_value%16
            dec_value=dec_value//16
            print(getHexChar(hex_value),end="")
    
    def getHexChar(dec_digit):
        if dec_digit < 10:
            return dec_digit
        if dec_digit == 10:
            return "A"
        if dec_digit == 11:
            return "B"
        if dec_digit == 12:
            return "C"
        if dec_digit == 13:
            return "D"
        if dec_digit == 14:
            return "E"
        if dec_digit == 15:
            return "F"
    
    main()
    

1 个答案:

答案 0 :(得分:0)

虽然getHexChar返回单个字符串,但decToHex会在运行时打印单个数字。从代码中获得预期输出的最小变化可能是:

def main():
    og_dec_value = int(input("Enter decimal value: "))
    print(og_dec_value,"is equal to",decToHex(og_dec_value), "in hexadecimal")

def decToHex(dec_value):
    ret_val = str()
    while dec_value > 0:
        hex_value=dec_value%16
        dec_value=dec_value//16
        ret_val = getHexChar(hex_value) + ret_val
    return ret_val

def getHexChar(dec_digit):
    if dec_digit < 10:
        return str(dec_digit)
    if dec_digit == 10:
        return "A"
    if dec_digit == 11:
        return "B"
    if dec_digit == 12:
        return "C"
    if dec_digit == 13:
        return "D"
    if dec_digit == 14:
        return "E"
    if dec_digit == 15:
        return "F"

main()

那个偏僻。我真的不确定hex()的问题是什么。如果我正在寻找另一种转换为十六进制字符串表示的方式,我会(如Moinuddin Quadri所建议的)选择相应的格式'{0:x}'.format(int(dec))'%x' % int(dec)如果你更喜欢旧式(你可能)不应该)。

如果现在仍然是你想要的,并且你想要保持你的阳离子,你可以通过这样做至少显着简化getHexChar()

def getHexChar(dec_digit):
    return '{:x}'.format(range(16)[dec_digit])

或者我们格式化确实是一种诅咒:

def getHexChar(dec_digit):
    return str((tuple(range(10)) + ('a', 'b', 'c', 'd', 'e', 'f'))[dec_digit])