Slip and Slide confusion


#1

Heya

I've been understanding everything in regards to bitwise operations up to this task

It's asking to create a function which takes 2 arguments. The 2nd argument indicates which bit in the 1st argument needs to be flipped.

So I would understand you would do it as such:

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

Which flips nth number from the right

But it won't accept that. This is what the task wants:

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

I'm not understanding why I need slide the 2nd argument into a 1 bit mask and then use that mask to indicate where the flip should be. Why can't I just use the 2nd argument as the indicator which bit in the 1st argument needs to be flipped?
What am I missing?


#2

Simply put, n is like an index. Indices start at 0. Without subtracting 1 from n, n would start at 1 and that just won't cut it.


#4

A post was split to a new topic: Slipe and slide confusion


#7

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