Slip and Slide: Unsupported Operand


#1

def flip_bit(number,n):
a=bin(number)
mask=(0b1<<n)
desired=a^mask
print bin(desired)
flip_bit(20,5)
flip_bit(7,2)
i am getting unsupported operand error


Slip and Slide
#2

Hi @netsolver19307,

The bin function converts an integer to a binary string. See Python: Built-in Functions: bin. You cannot use the << operator on a string. Instead of doing this …

  a=bin(number)

… perform the shift operation directly on 0b1. To compute mask, shift 0b1 by 1 less than the position of the bit that is to flipped, as follows …

  mask = 0b1 << n - 1

Use ^ to compute result

  result = number ^ mask

Now that the bitwise operations have been performed, you can use bin to convert to a string …

  return bin(result)

#3

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