Search code examples
pythonbitwise-operatorsbitbitboard

Modify a bit at a given position in a int from left to right:


I have been trying to come up with a funtion were given a int it would modify a bit at a given position using bitwise operations:

For example:

modify_bit(int, pos)

modify_bit(0b10000, 1) should return 0b11000

Or modify_bit(0b10000, 6) should return 0b100001

I have done research but have not found any funtions that modify a bit at a given position in a bitboard from left to right were instead all the funtions that I have found that might be what I am looking for modify a bit from the postions right to left.

Thanks in advance!


Solution

  • This is a very unusual thing to want to do. Are you sure this is the spec? You don't normal want to extend a sequence of bits like this. However, this does what you ask:

    def setbit( val, pos ):
        bits = len(bin(val))-2
        if pos >= bits:
            val <<= (pos-bits)
            bits = pos + 1
        val |= 1 << (bits - pos - 1)
        return val
    
    def clrbit( val, pos ):
        bits = len(bin(val))-2
        if pos >= bits:
            val <<= (pos-bits)
            bits = pos + 1
        else:
            val &= ~(1 << (bits - pos - 1))
        return val
    
    print( bin(setbit( 0b10000, 1 )))
    print( bin(setbit( 0b10000, 6 )))