【问题标题】:Bitwise Operations to change 2 LSB更改 2 LSB 的按位运算
【发布时间】:2017-08-27 19:43:02
【问题描述】:

假设我有一个数字列表:

l = [30, 31, 32, 33]

在二进制中,这与

相同
l = [00011110, 00011111, 00100000, 00100001]

使用二进制运算,我想将 最低 2 个有效位 设置为任意随机值,但 保留 6 个最高有效位。这方面的一个例子可能是:

l_new = [00011111, 00011101, 00100010, 00100010]

如何使用 python 中的 numpy 库来做到这一点?

【问题讨论】:

  • 没有 NumPy 也可以轻松完成。

标签: python-3.x numpy bit-manipulation binary-operators


【解决方案1】:

你可以使用按位异或:

a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, a.shape)
a
# array([131,  79, 186,  90, 102, 179, 247,  28,  58,  60])
b
# array([2, 0, 2, 1, 0, 0, 2, 0, 3, 3])
a^b
# array([129,  79, 184,  91, 102, 179, 245,  28,  57,  63])

证明正确性:

a = np.random.randint(0, 256, (10,))
b = np.random.randint(0, 4, (1000000,) + a.shape)

# show it leaves high 6 unchanged:
print(np.all(252&a == 252&(a^b)))
# show all low 2 values equally likely:
print(np.abs(np.array([np.histogram(c, np.arange(5)-0.5, normed=True)[0] for c in ((a^b)&3).T])-0.25).max())

# True
# 0.001595

【讨论】:

    【解决方案2】:

    您可以使用numpy.unpackbits

    l = np.random.randint(16,size=(10,)).astype(np.uint8)
    # [ 9 13  3 10 10]
    
    bits = np.unpackbits(l[:,np.newaxis],axis=1)
    # [[0 0 0 0 1 0 0 1]
    #  [0 0 0 0 1 1 0 1]
    #  [0 0 0 0 0 0 1 1]
    #  [0 0 0 0 1 0 1 0]
    #  [0 0 0 0 1 0 1 0]]
    
    bits[:,-2:] = np.random.randint(0,2,size=(bits.shape[0],2))
    # [[0 0 0 0 1 0 0 1]
    #  [0 0 0 0 1 1 0 1]
    #  [0 0 0 0 0 0 1 0]
    #  [0 0 0 0 1 0 0 1]
    #  [0 0 0 0 1 0 0 1]]
    
    np.squeeze(np.packbits(bits,axis=1))
    # [ 9 13  2  9  9]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 2013-01-07
      相关资源
      最近更新 更多