14/14 Working but not


#1

The code doesn't work but it should.

def flip_bit(number,n):
    
    n = n-1
    mask = 0b1 << n
    
    print "Nth bit is: "
    print n +1
    print bin(n+1)
    print'-' *8
    print "Mask is: "
    print mask
    print bin(mask)
    print '-' *8
    print "Number to be flipped: "
    print number
    print bin(number)
    print '-' *8
    
    result  = n ^ number
    
    print "The result is: "
    print result
    print bin(result)
    return bin(result)
    
flip_bit(0b1010101,3)


output:

Nth bit is: 
3
0b11
--------
Mask is: 
4
0b100
--------
Number to be flipped: 
85
0b1010101
--------
The result is: 
87
0b1010111

as you can see the mask lines up with the correct bit, but it flips the one to the right of it. If i don't decease n the bit to the left of the n bit is flipped. I can't figure out what is happening.


#2

The result should be 81 when we XOR 85 and 3-1.

0b1010101
0b0000001
0b0000010 << 1
0b0000100 << 2
---------
0b1010001  => 81

#3

@n_rii
To give you a visual
https://discuss.codecademy.com/t/3-14-plz-print-code-so-i-can-compare/10465/2?u=leonhard.wettengmx.n


#4

Based on the explanation below is the working code

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

flip_bit(0b1111,2)