按位操作改变2 LSB

时间:2017-04-03 03:44:36

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

假设我有一个数字列表:

l = [30, 31, 32, 33]

在二进制文件中,这与

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

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

l_new = [00011111, 00011101, 00100010, 00100010]

如何使用python中的numpy库?

2 个答案:

答案 0 :(得分:1)

您可以使用按位xor:

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

答案 1 :(得分:1)

您可以使用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]