十六进制到二进制程序 - Python

时间:2012-04-10 11:55:35

标签: python

我正在做一份修改试卷。这不是我想要帮助的特定问题,但我不确定在输入某些数据时程序输出错误的原因。

def Binary(Hex):
    Result = ''
    ErrorFound = False
    BinaryEquivalent = ''
    EmptyInput=""
    for ThisHexDigit in Hex:
        if ThisHexDigit in ['1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F']:
            if ThisHexDigit == '0': BinaryEquivalent = '0'
            elif ThisHexDigit == '1': BinaryEquivalent = '1'
            elif ThisHexDigit == '2': BinaryEquivalent = '2'
            elif ThisHexDigit == '3': BinaryEquivalent = '3'
            elif ThisHexDigit == '4': BinaryEquivalent = '4'
            elif ThisHexDigit == '5': BinaryEquivalent = '5'
            elif ThisHexDigit == '6': BinaryEquivalent = '6'
            elif ThisHexDigit == '7': BinaryEquivalent = '7'
            elif ThisHexDigit == '8': BinaryEquivalent = '8'
            elif ThisHexDigit == '9': BinaryEquivalent = '9'
            elif ThisHexDigit == 'A': BinaryEquivalent = '10'
            elif ThisHexDigit == 'B': BinaryEquivalent = '11'
            elif ThisHexDigit == 'C': BinaryEquivalent = '12'
            elif ThisHexDigit == 'D': BinaryEquivalent = '13'
            elif ThisHexDigit == 'E': BinaryEquivalent = '14'
            elif ThisHexDigit == 'F': BinaryEquivalent = '15'
            Result = Result + BinaryEquivalent
        elif ErrorFound == True:
            print('You have made a mistake')
        elif Hex==EmptyInput:
            print('Empty input, try again.')

    return Result

是的,我知道这是一个过于复杂的代码,但它在考试卷中,所以我必须使用它。就是这样,除了所有BinaryEquivalent字符串都是BinaryEquivalent = ''而不是内部有数字。

问题是我在程序显示时输入两个字符。例如,输入“BBB”将输出11,“BBBBBB”也将输出。

3 个答案:

答案 0 :(得分:2)

您应该将return语句放在for周期之外。

答案 1 :(得分:0)

return语句位于for循环内,因此只进行了一次迭代,它应该是:

for ThisHexDigit in Hex:
    #code

return result

而不是:

for ThisHexDigit in Hex:
    #code
    return result

答案 2 :(得分:0)

只有当十六进制数字是单个十六进制数字时,您的解决方案才有效。如果你想转换更长的数字,你将不得不做一些更正。

  1. Result可以是简单的int,以0
  2. 开头
  3. 所有BinaryEquivalent应该是整数,因此请使用BinaryEquivalent = 0
  4. 在for循环中,您必须增加结果,请使用:Result = 16 * Result + BinaryEquivalent