【问题标题】:python convert a binary string to a structure sutiable for bitwise operatorspython将二进制字符串转换为适合按位运算符的结构
【发布时间】:2013-10-03 09:48:39
【问题描述】:

我有一个表示二进制数的 unicode 字符串列表,例如“010110”。

我希望执行按位运算,那么如何将其转换为可以对这些执行按位运算的结构(最好是无符号整数)?

【问题讨论】:

    标签: python binary type-conversion


    【解决方案1】:

    int() 与“base”选项一起使用。

    int("010110", 2)
    

    【讨论】:

      【解决方案2】:

      您可以将字符串转换为 int,然后对其使用常规移位运算符:

      >>> x = int("010110", 2)
      >>> x >> 3
      2
      >>> x << 3
      176
      

      【讨论】:

      • @Jon 谢谢,添加; 的习惯很难改掉。
      【解决方案3】:

      使用 int() 是最明显和最有用的方法。但你没有说你是否需要这些整数。

      以防万一,那么:

      x = '1010100100'
      intx = int(x,2)
      x
      0x2a4
      intx >> 5
      0x15
      bin(intx>>5)
      '0b10101'
      x[:-5]
      '10101'
      
      intx << 3
      0x1520
      bin(intx<<3)
      '0b1010100100000'
      x + '0'*3
      '1010100100000'
      

      实际的转变速度较慢,但​​最终结果不一定,也没有您想象的那么慢。这是因为即使在大多数现代架构上实际移位可能是单个周期,而切片显然有更多指令,但仅查找参数等就有很多开销,这使得它没有太大区别。

      # Shifts are about 40% faster with integers vs. using equivalent string methods
      In [331]: %timeit intx>>5
      10000000 loops, best of 3: 48.3 ns per loop
      
      In [332]: timeit x[:-5]
      10000000 loops, best of 3: 69.9 ns per loop
      
      In [333]: %timeit x+'0'*3
      10000000 loops, best of 3: 70.5 ns per loop
      
      In [334]: %timeit intx << 3
      10000000 loops, best of 3: 51.7 ns per loop
      
      # But the conversion back to string adds considerable time,
      # dependent on the length of the string
      In [335]: %timeit bin(intx>>5)
      10000000 loops, best of 3: 157 ns per loop
      
      In [338]: %timeit bin(intx<<3)
      1000000 loops, best of 3: 242 ns per loop
      
      # The whole process, including string -> int -> shift -> string,
      # is about 8x slower than just using the string directly.
      In [339]: %timeit int(x,2)>>5
      1000000 loops, best of 3: 455 ns per loop
      
      In [341]: %timeit int(x,2)<<3
      1000000 loops, best of 3: 378 ns per loop
      

      int(x,2) 可能仍然是您最好的选择,但如果您使用它,只是一些其他的优化想法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-02
        • 2021-02-24
        相关资源
        最近更新 更多