如何修改整数位?

时间:2012-08-29 08:31:52

标签: python binary bit

我有一个值为70b00000111)的整数。我想用130b00001101)的函数替换它。替换整数位的最佳算法是什么?

例如:

set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?

5 个答案:

答案 0 :(得分:28)

你只需要:

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

注意位数(index)来自0,其中0是最低有效位。

另请注意,新值已返回,无法像您显示的那样“就地”修改整数(至少我不这么认为)。

答案 1 :(得分:24)

这些适用于任何大小的整数,甚至大于32位:

def set_bit(value, bit):
    return value | (1<<bit)

def clear_bit(value, bit):
    return value & ~(1<<bit)

如果你喜欢简短,你可以使用:

>>> val = 0b111
>>> val |= (1<<3)
>>> '{:b}'.format(val)
'1111'
>>> val &=~ (1<<1)
'1101'

答案 2 :(得分:8)

您可以使用按位运算。 http://wiki.python.org/moin/BitwiseOperators

如果要将给定位设置为1,则可以在给定位置使用按位'或'1:

0b00000111 | 0b00001000 = 0b00001111

要将给定位设置为0,您可以使用按位'和'

0b00001111 &amp; 0b11111011 = 0b00001011

请注意,0b前缀用于二进制数,0x用于十六进制。

答案 3 :(得分:0)

网站管理员向我指出了此事...

我仍然对如何使用上述功能设置适当的位模式感到困惑

我可能还想在运行时更改字节,但一次只更改1位。...即关闭TEI(TEI = False)

有想法吗?

mask = 0b00000000

TEI = True
TRANSPORT_PRIORITY = False

if TEI == True:
    mask = 0b10000000 | mask
elif TEI == False:
    mask = 0b01111111 & mask

if TRANSPORT_PRIORITY == True:
    mask = 0b01000000 | mask
elif TRANSPORT_PRIORITY == False:
    mask = 0b10111111 & mask


print(bin(mask))
print(hex(mask))

预先感谢

尼尔

答案 4 :(得分:0)

按照提供的示例进行操作,听起来好像您正在寻找以整数交换位。 例如,在7 (0b00000111)中,如果在第3和1st位置交换位,则得到13 (0b00001101)

我将以下内容用作函数签名swap_bits(val, i, j)

什么是最好的算法?好吧,下面的算法需要恒定的时间O(1)。

def swap_bits(val, i, j):
    """
    Given an integer val, swap bits in positions i and j if they differ
    by flipping their values, i.e, select the bits to flip with a mask.
    Since v ^ 1 = 0 when v = 1 and 1 when v = 0, perform the flip using an XOR.
    """
    if not (val >> i) & 1 == (val >> j) & 1:
        mask = (1 << i) | (1 << j)
        val ^= mask
    return val

示例:

 >>> swap_bits(7, 3, 1)
 13

代码利用了一些琐碎的技巧,这是Sean Anderson的good resource。我正在使用Python here提供代码段。

相关问题