So I came on here to ask the SAME exact question. I put exactly what you had in your original code, thinking that is what was being asked. I'm confused by this as well. Maybe i'm just not reading it properly but it's not making sense to me.
Sau we wish to flip the fourth bit in
0b1010101 so we pass to the function,
Looking at how we describe the bits,
bit 1 is the first on the right. If our
1 then there will be a shift to the left which will target
bit 2. Not the bit we wish to filp. Likewise if we flip the bit targeted by shift to the left of 4, we will be flipping
n - 1.
>>> def flip_bit(number, n): result = number ^ n return bin(result) >>> flip_bit(0b1010101,4) '0b1010001' >>> def flip_bit(number, n): result = number ^ n - 1 return bin(result) >>> flip_bit(0b1010101,4) '0b1010110' >>>
Does the above look right? It uses the code from the earlier opening post, which is not quite right.
Above we mention
shift to the left; where does that come in? It comes in as a mask that we create ahead of time.
>>> def flip_bit(number, n): mask = 0b1 << n-1 return bin(number ^ mask) >>> flip_bit(0b1010101,4) '0b1011101' >>>
Now we can properly demonstrate that happens when we do not subtract 1 from
>>> def flip_bit(number, n): mask = 0b1 << n return bin(number ^ mask) >>> flip_bit(0b1010101,4) '0b1000101' >>>
Your mask is not right for this problem. To flip the third bit, the mask should be
3. Four will flip only one bit, three will flip two. (I get it if your intent is to flip two bits.)
4 => 0b100 3 => 0b11
To create a flip_bit mask for only one bit, we start with
1 and shift left
n - 1 times.
0b1 << 1 => 0b10 0b10 << 1 => 0b100
To write a one line return statement,
return number ^ (0b1 << n -1)
That's the less obvious aspect of it. A learner is better familiarizing themselves with what binary numbers look like. Granted, a single bit flip mask can be written as a power of 2. It's still going to be
n - 1.
mask = 2 ** (n - 1)
>>> n = 3 >>> 0b1010101 ^ (0b1 << n - 1) 81 >>> bin(0b1010101 ^ (0b1 << n - 1)) '0b1010001' >>>
>>> bin(0b1010101 ^ (2 ** (n - 1))) '0b1010001' >>>
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.