def set_bit(v, index, x):
"""Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value."""
mask = 1 << index # Compute mask, an integer with just bit 'index' set.
v &= ~mask # Clear the bit indicated by the mask (if x is False)
if x:
v |= mask # If x was True, set the bit indicated by the mask.
return v # Return the result, we're done.
>>> set_bit(7, 3, 1)
15
>>> set_bit(set_bit(7, 1, 0), 3, 1)
13
这些函数适用于任何大小的整数,甚至大于32位:
如果你喜欢短的东西,你可以用:
可以使用按位操作。 http://wiki.python.org/moin/BitwiseOperators
如果要将给定位设置为1,则可以在给定位置使用带1的按位“或”:
0b0000111|0b0001000=0b0001111
若要将给定位设置为0,可以使用按位“和”
0b0001111&;0b11111011=0b0001011
注意,0b前缀表示二进制数,而x表示十六进制数。
你只需要:
注意,位号(
index
)来自0,0是最低有效位。还要注意,新值是return,没有办法像您显示的那样修改整数“就地”(至少我不这么认为)。
相关问题 更多 >
编程相关推荐