【问题标题】:python hex to decimal using for loop [duplicate]python十六进制到十进制使用for循环[重复]
【发布时间】:2014-02-19 10:13:46
【问题描述】:
import math
def hexToDec(hexi):
    result = 0
    for i in range(len(hexi)-1,-1,-1):
        if hexi[i] == 'A':
            result = result + (10 * math.pow(16,i))
        elif hexi[i] == 'B':
            result = result + (11 * math.pow(16,i))
        elif hexi[i] == 'C':
            result = result + (12 * math.pow(16,i))
        elif hexi[i] == 'D':
            result = result + (13 * math.pow(16,i))
        elif hexi[i] == 'E':
            result = result + (14 * math.pow(16,i))
        elif hexi[i] == 'F':
            result = result + (15 * math.pow(16,i))
        else:
            result = result + (int(hexi[i]) * math.pow(16,i))
    return result

即使在反转范​​围顺序并重新导入之后,我仍然得到相同的结果。

【问题讨论】:

  • 为什么int(hexi,16)不删呢?它似乎能够处理 py3 中的大量数字。 (也许long(hexi,16) 在 py2 中工作?)

标签: python hex decimal number-systems


【解决方案1】:

虽然可以有这样漂亮的答案

x = int("FF0F", 16)

了解原始代码是如何出错的也很重要。更正后的版本应该是:

import math
def hexToDec(hexi):
    result = 0
    for i in range(len(hexi)):
        cur_pow = len(hexi) - i  - 1
        if hexi[i] == 'A':
            result = result + (10 * math.pow(16,cur_pow))
        elif hexi[i] == 'B':
            result = result + (11 * math.pow(16,cur_pow))
        elif hexi[i] == 'C':
            result = result + (12 * math.pow(16,cur_pow))
        elif hexi[i] == 'D':
            result = result + (13 * math.pow(16,cur_pow))
        elif hexi[i] == 'E':
            result = result + (14 * math.pow(16,cur_pow))
        elif hexi[i] == 'F':
            result = result + (15 * math.pow(16,cur_pow))
        else:
            result = result + (int(hexi[i]) * math.pow(16,cur_pow))
    return result

无论您是否“反向”循环,幂顺序和hexi 的索引都应该以相反的方向迭代,一个增加另一个减少。

现在您可以忘记这一点并使用其他人建议的答案。

【讨论】:

  • +1 用于像操作所需的那样使用 for 循环。
  • 我会通过大量使用+= 来改进它。
  • 并且每个字母的大小写显然不是最好的方法,即使你保持循环的想法不变。 result += (ord(hexi[i]) - ord('A') + 10) * (16 ** cur_pow)(甚至…<< (4 * cur_pow))将进一步改进该解决方案;-)
  • 嗯,这些观点绝对是正确的,并且已经被其他很好的答案很好地解决了。我试图指出 OP 面临并且无法弄清楚的逻辑错误——这不是真正的问题吗? ;-)
  • 感谢您的回答。我需要一个 for 循环,因为我的老师想教我们循环字符串和转换数字系统的组合。因此,我不认为这个问题是重复的。
【解决方案2】:

在python中如果你想重新导入一些东西,你需要重新启动python进程,或者手动复制你在python中更改的文件的内容,或者更方便地使用ipython中的℅cpaste。

重新导入在 python 中不起作用。

【讨论】:

  • 对不起,这实际上是我所做的。在 IDLE 中,我运行了模块并重新启动了 python 进程。
【解决方案3】:

你观察到你的 for 循环生成的索引了吗?

无论您采用何种方向扫描输入字符串(向前或向后),索引都会为最左边的数字生成0,为最右边的数字生成len(i)-1。因此,当您使用索引计算math.pow(16,i) 中的“数字位置”时,您正在计算输入字符串的第一个字符是最右边(最低有效)的数字。

尝试使用math.pow(16, len(hexi)-1-i)...

进行此校正后,扫描方向(向前或向后)无关紧要。你可以将你的 for 循环重写为for i in range(len(hexi)):

另外,你知道你不需要导入 math 模块来计算能力吗?您可以使用** 运算符:2**416**i16**(len(hexi)-1-i)

【讨论】:

    【解决方案4】:
    hexToDec = lambda hexi: int(hexi,16)
    

    或在 Python 2 中:

    hexToDec = lambda hexi: long(hexi,16)
    

    ?

    【讨论】:

      【解决方案5】:

      其他人已经展示了快速的方法,但是因为你希望它在一个 for 循环中......你的问题在于你的循环参数,权力需要是字符串的 len - 当前位置 - 1 就像@ YS-L 在他的回答中也没有使用 if-else 你有 dictionary! (您也可以改为检查'A' <= myCurrentChar <= 'F'

      import math
      def hexToDec(hexi):
          result = 0
          convertDict = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
          for i in range(len(hexi)):    
              if str.isdigit(hexi[i]):
                  result += int(hexi[i]) * math.pow(16, len(hexi) - i - 1)
              else:
                  result += convertDict[hexi[i]] * math.pow(16, len(hexi) - i - 1)
      
          return int(result)
      
      print hexToDec("FFA")
      

      输出:

      4090
      

      【讨论】:

        【解决方案6】:

        太多elifpow...只是shift (result = result * 16)add (ord(ch) - ord(...)) 一些东西喜欢

        """ Manual hexadecimal (string) to decimal (integer) conversion
            hexadecimal is expected to be in uppercase
        """
        def hexToDec(hexi):
          result = 0;
        
          for ch in hexi:
            if 'A' <= ch <= 'F':
              result = result * 16 + ord(ch) - ord('A') + 10
            else:
              result = result * 16 + ord(ch) - ord('0')
        
          return result;
        

        【讨论】:

        • @volcano:谢谢! 'A'= 'A' 和 ch
        【解决方案7】:

        单行 - (不是很可读) - 但适用于小写并处理 0x 前缀

        sum(16**pwr*(int(ch) if ch.isdigit() else (ord(ch.lower())-ord('a')+10))
            for pwr, ch in enumerate(reversed(hexi.replace('0x',''))))
        

        【讨论】:

          猜你喜欢
          • 2013-06-13
          • 2023-03-14
          • 2011-12-09
          • 2017-09-28
          • 1970-01-01
          • 2023-03-19
          • 2018-07-26
          • 2014-08-24
          • 2016-01-05
          相关资源
          最近更新 更多