【问题标题】:Python hexadecimal comparisonPython 十六进制比较
【发布时间】:2010-12-25 16:16:29
【问题描述】:

我遇到了一个问题,希望有人能帮我解决!

我有一个十六进制数字 = '0x00000000' 的字符串,这意味着:

0x01000000 = apple  
0x00010000 = orange  
0x00000100 = banana   

所有这些组合都是可能的。即0x01010000 = apple & orange

我如何从我的字符串中确定它是什么水果?我用所有组合制作了一本字典,然后与它进行比较,它有效!但我想知道一种更好的方法。

【问题讨论】:

    标签: python hex


    【解决方案1】:

    通过使用int() 内置函数并指定一个基数,将您的字符串转换为整数:

    >>> int('0x01010000',16)
    16842752
    

    现在,您有了一个代表位集的标准整数。使用&| 和任何其他按位运算符来测试各个位。

    >>> value  = int('0x01010000',16)
    >>> apple  = 0x01000000
    >>> orange = 0x00010000
    >>> banana = 0x00000100
    >>> bool(value & apple) # tests if apple is part of the value
    True
    >>> value |= banana     # adds the banana flag to the value
    >>> value &= ~orange    # removes the orange flag from the value
    

    现在,如果您需要转换回您的字符串:

    >>> hex(value)
    '0x1000100'
    

    【讨论】:

    • 它被称为按位运算,您可以将值组合在一起以获得组合结果。如果 64 (apple) 被 OR'ed 到 80(所有 OR 值的总和),测试 ((64|80) = 80) 将返回 true。 wiki.python.org/moin/BitwiseOperators
    • 感谢大家的快速解答!我将阅读按位运算符!
    【解决方案2】:

    您可以首先将您的字符串转换为整数:

    s = "0x01010000"
    i = int(s, 16) #i = 269484032
    

    然后,您可以为水果设置一个列表:

    fruits = [(0x01000000, "apple"), (0x00010000, "orange"), (0x00000100, "banana")]
    

    确定你有什么水果就足够了:

    s = "0x01010000"
    i = int(s, 16)
    for fid,fname in fruits:
        if i&fid>0:
            print "The fruit '%s' is contained in '%s'" % (fname, s)
    

    这里的输出是:

    The fruit 'apple' is contained in '0x01010000'
    The fruit 'orange' is contained in '0x01010000'
    

    【讨论】:

      【解决方案3】:
      def WhichFruit(n):
          if n & int('0x01000000',16):
              print 'apple'
          if n & int('0x00010000',16):
              print 'orange'
          if n & int('0x00000100',16):
              print 'banana'
      
      WhichFruit(int('0x01010000',16))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-26
        相关资源
        最近更新 更多