How to modify bits in an integer?

前端 未结 4 2278
暖寄归人
暖寄归人 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 22:01

    These work for integers of any size, even greater than 32 bit:

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

    If you like things short, you can just use:

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

提交回复
热议问题