How to modify bits in an integer?

前端 未结 4 2281
暖寄归人
暖寄归人 2020-12-08 21:01

I have an integer with a value 7 (0b00000111) And I would like to replace it with a function to 13 (0b00001101). What is

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 21:55

    You just need:

    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
    

    Note that bit numbers (index) are from 0, with 0 being the least significant bit.

    Also note that the new value is returned, there's no way to modify an integer "in place" like you show (at least I don't think so).

提交回复
热议问题