Slip and Slide - What's wrong with this?


#1


The code below returns 0b11011 instead of 0b101. How do I fix this?


def flip_bit(number, n):
    mask = number << n
    erised = number ^ mask
    return bin(erised)

print flip_bit(0b111, 2)


#2

@irkengirl,

def flip_bit(number, n):
    print format(number, '#010b')
    mask = number << n
    print format(mask, '#010b')
    erised = number ^ mask
    print format(erised, '#010b')
    return bin(erised)

print flip_bit(0b111, 2)


print("=======================")
print "== Bitwise XOR  7 ^ 28 =================="
print " "    
print "XOR | 0 1"
print "----+----"
print "  0 | 0 1"
print "  1 | 1 0"
print format(7, '#010b') +" ("+str(7) +")"
print format(28, '#010b') +" ("+str(28) +")"
print format(7^28, '#010b')
print 7 ^ 28 # Bitwise XOR

[output]

0b00000111
0b00011100
0b00011011
0b11011
=======================
== Bitwise XOR  7 ^ 28 ==================
 
XOR | 0 1
----+----
  0 | 0 1
  1 | 1 0
0b00000111 (7)
0b00011100 (28)
0b00011011
27

11. The man behind the mask is giving me pronlems
Bit mask
#3

mask = 0b1 << n - 1 should do the trick

This is just following the example that shows to use 1 = 0b1 and slide by the nth bit. Remember in the example it says to slide over to the 10th bit you use 9 since the sliding starts from the 1st bit.

Hope that helps.


#4

Yeah, I need help on Slip and Slide it doesn't work why?


#5

I tried various examples, and then tried the code pasted here on the forum. However, I still get error:

Oops, try again. Your function fails on flip_bit('0b111', 2). It returns "0b1001" when it should return "0b101".

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

print flip_bit(0b111, 2)

#6

it is 0b1<< n not number<< n. you have to left shift the bit by n , not the number.


#10