Error when calling function

0

When I call this function:

def check_bit4(input):
  mask = "0b010"
  desired = input & mask
  if desired > 0:
    return "on"
  else:
    return "off"

This error appears:

Traceback (most recent call last):
  File "python", line 9, in <module>
  File "python", line 3, in check_bit4
TypeError: unsupported operand type(s) for &: 'int' and 'str'

I searched, but did not find a solution to the error

    
asked by anonymous 25.07.2018 / 17:18

2 answers

1

Is trying to do a bitwise operation with inteiro and a string ? That does not make sense, do you agree?

I think what you want is something like:

def check_bit4(input):
  mask = 0b010

  desired = input & mask

  if desired > 0:
    return "on"
  else:
    return "off"

print(check_bit4(0b1))    # off
print(check_bit4(0b1111)) # on
print(check_bit4(0b1010)) # on
    
25.07.2018 / 17:29
0

Now, a suggestion: to make functions a bit more generic. Example - A function that gives the value of the bit n of a number: (Python3)

def bit(n,input):
   n=n-1
   return (input & 2**n) // 2**n

bit(1,3)   # 1
bit(2,3)   # 1
bit(3,3)   # 0
    
26.07.2018 / 17:32