-1

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!

Jalrux
  • 7
  • 1
  • 9
  • What you're asking isn't sensible. You don't treat bit strings this way. It's either a 5-bit number or a 6-bit number. You probably can't see that I've posted 3 different solutions and deleted them. What's the use case for this? In what context does this make sense? – Tim Roberts Mar 08 '21 at 23:22

1 Answers1

1

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 )))
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30