Im a bit confused with this lesson…
Lets start with the example they give is first:
a = 0b101 # Tenth bit mask mask = (0b1 << 9) # One less than ten desired = a ^ mask
Let’s say that I want to turn on the 10th bit from the right of the integer
Instead of writing out the entire number, we slide a bit over using the
We use 9 because we only need to slide the mask nine places over from the first bit to reach the tenth bit.
What I discovered is that:
1.We dont actually need the parentheses around (0b1 << 9)
2.0b1 << 9 is the same as 0b1 << 10 - 1, we get the same binary number - 0b1000000101
So to get to the 10th bit it doesn’t matter which way we choose, because they both give you the same result…right?
Define a function called
flip_bit that takes the inputs
(number, n) .
Flip the nth bit (with the ones bit being the first bit) and store it in
Return the result of calling
What do they mean with (with the ones bit being the first bit) ?
Lets look at the Codecademy solution and use the numbers from the example they gave us:
def flip_bit(number, n): mask = 0b1 << (n - 1) result = number ^ mask return bin(result) print flip_bit(0b101, 9)
Here we want to flip the 9th bit…n inside the mask variable turns to 9 so that we get 0b1 << (9-1), BUT if we wanted, AND knew, that that we wanted to flip the 9th bit, why not just call the the function with 8 and lose the - 1 part inside the mask variable, so that the mask variable would look like this mask = 0b1 << n , with other words mask = 0b1 << 8?
Is it because they want us to make sure that if somebody else uses the function, besides us, gets to flip the right bit(9th bit) when they enter 9?
How do we flip a bit the other way around…with the right shift, how is the mask going to look?
Lest say we have the number 100000101, and I want to flip the third bit from right to left, so that the number changes to 101000101?