Slip and Slide - why the n-1


#1




it works because I saw the solution on a different topic, but those do not explain why the n -1.

Can someone drop their 2 cents?


def flip_bit(number, n):
    mask = (0b1 << n-1)
    result = number ^ mask
    
    return bin(result)
    
print flip_bit(0b111, 3)


#2

It's not immediately evident but, n - 1 converts a position number (from the right) to a degree. Were we to desire a flip of the first bit (n == 1), we would not want to shift at all, hence n-1. This logic is consistent universally no matter how many bits.

should return 0b11.


#4

I think this exercise can use some more explanation. I understand that it's rarely used but it's just for the sake of learning something that exists in a language


#5

That's where extra reading comes in. The author has here only introduced the concepts; it is up to us as self-learners to follow through with our own research, study and practice. This site is not a be-all-to-end-all, but just a beginning. Some will continue on, others will quit. Not our responsibility.


#6

Yes , true but I don't mean the idea I mean the instructions of the exercise itself


#7

Not going to happen, at least not in this iteration of the courseware. A newer version of this course is slated to appear in the new year. We'll have to see if anything changes come then.


#8

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