【问题标题】:bitwise operation on string representation of binary number python 2.7二进制数python 2.7的字符串表示的按位运算
【发布时间】:2016-05-13 15:06:31
【问题描述】:

我想对二进制数的两个字符串表示形式执行按位或,但我不知道如何将字符串转换为原始二进制。

a = '010110'
b = '100000'

一个 | b

应该产生: 110110

然后我想计算 on 位数。
这应该返回:
4

【问题讨论】:

    标签: python bit-manipulation


    【解决方案1】:

    您可以使用内置的int() function 将字符串转换为二进制,并将 2 作为基数传递:

    a = int('010110', 2)
    b = int('100000', 2)
    

    然后对两个值进行 OR 并通过转换为字符串并计算“1”字符来计算位数:

    print bin(a | b).count("1")
    

    【讨论】:

      【解决方案2】:

      您可以编写一个派生自str 的自定义类,并覆盖其负责二元或运算符| 的魔术方法。

      有很多方法可以实现 OR。 @samgak 在他的回答中已经描述了可能最简单的一个,您可以使用 int 并将基数指定为 2,然后使用其 | 运算符:

      class bitstr(str)
          def __or__(self, other):
              return bin(int(self, 2) | int(other, 2))[2:]
              # need to slice because 'bin' prefixes the result string with "0b".
      

      你可以这样使用它:

      a = '010110'
      b = bitstr('100000')
      
      print(bitstr(a) | b)
      # Output: 110110
      

      您发现您需要在某处转换为bitstr,但这并不重要。此外,对于除| 运算符之外的所有其他操作,我们自定义的bitstr 的行为与普通的str 字符串完全相同,因此您可以在任何地方使用它。

      See this code running on ideone.com

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 2012-09-25
        • 2014-06-25
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        相关资源
        最近更新 更多