Why does my flip_bit function return the wrong number?
Answer
There are a few common mistakes with this exercise that are listed below:
Make sure your mask is created by shifting a 1 left by n - 1 digits. If we shift by n, that is one too many, since the 1 starts off in the first position.
The result you return is the result of XORing together the number passed to the function and the mask you just created.
Be sure to wrap the result in bin() when you return it!
def flip_bit(number, n):
bit_to_flip = 0b1 << (n -1) #Ok now how to explain that? Flip the nth bit .
result = number ^ bit_to_flip #(with the ones bit being the first bit) and store it in result
return bin(result)
why ,nth bit, = (n-1) where is that come from? 0b1 is the first bit, and then we are selecting the bit to flip, but why like this? (n-1)?
As you said correctly: 0b1 is the first bit. So it is already given. If you want to flip the 10th bit (like in the example) you have to subtract 1 from 10. If you would not do so, you would end up at the 11th bit.
If I were to convert this code into Python 3-appropriate syntax, how would I deal with the βnβ paramater? I ran it inside Repl.it and tried to tweak accordingly:
def flip_bit(number,n):
bit_flipper = 0b1 << (n-1)
result = bit_flipper ^ number
return bin(result)
print (flip_bit(0b1001))
I think you are thinking of bytes (usually composed of 8 bits), not base 2 (base 2 is just a counting method used by bytes, like base 10 is the counting method most people use in ordinary life outside of programming).
A bit is just a 0 or a 1 when used in binary (base 2) counting, there is no limit on how many places the number can extend to. Just like in normal base ten counting, you can count up as high as you like in base 2 to express any integer number, using however many places are necessary to do so.
just asking is the intended result for the function 0b1000001, the program wanted me to get 0b101
from the argument of (0b111,2) but the result is way bigger.
Just wondering, do we have to use XOR operator in this exercise or we can use OR operator instead? I donβt know why OR operator makes more sense to me