The code doesn't work but it should.
def flip_bit(number,n): n = n-1 mask = 0b1 << n print "Nth bit is: " print n +1 print bin(n+1) print'-' *8 print "Mask is: " print mask print bin(mask) print '-' *8 print "Number to be flipped: " print number print bin(number) print '-' *8 result = n ^ number print "The result is: " print result print bin(result) return bin(result) flip_bit(0b1010101,3) output: Nth bit is: 3 0b11 -------- Mask is: 4 0b100 -------- Number to be flipped: 85 0b1010101 -------- The result is: 87 0b1010111
as you can see the mask lines up with the correct bit, but it flips the one to the right of it. If i don't decease n the bit to the left of the n bit is flipped. I can't figure out what is happening.