# Y dis no work? 14. Slip and Slide

#1

cries in binary

``````def flip_bit(number, n):
result = number << n
return bin(result)``````

#2

Here:

``    result = number << n``

The `<<` operation alone will not return the `n`th bit.

Instead, why not try something like:

``    result = number ^ (0b1 >> n - 1)``

#3

You seem to have the wrong operation here. Left-Shifting the number just multiplies it:

``````>>> number = 5 # for example
>>> bin(number)
'0b101'
>>> bin(number << 2)
'0b10100'``````

in other words, you just take the pattern and move it to the left by a number of places. Therefore, using a mask like this:

``````>>>mask = 1 << 3
>>>bin(mask)
'0b1000'``````

so you have just one bit set true, in the (fourth) place. It's the fourth place because doing nothing (ie shifting by zero) leaves the first bit set `0b00001`, shifting by one moves it into the second place, and so on [see footnote].

Once you have the mask set up, you use the xor (`^`) operator to flip that bit in the original number.

``````def flip(bit, number):
mask=1 << (bit-1) # should check that bit >= 0 !
return number ^ mask``````

By the way,

has the shift operator pointing the wrong way!

[footnote]: in the real world, the rightmost bit usually labelled zero, so all the bits run from 0—15 or 0—63 etc, so you don't have to do the subtraction.

Hope that helps

Tim F

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.