The Man behind the bit


#1

I’m trying to modify the code to allow the user to pass a decimal, have the function convert it to binary and then perform the bitmask operation. However I’m struggling to understand the output datatype of the the bin() function.

Here is my code:

def check_bit4(input):
  num = bin(str(input))
  mask = 0b1000
  desired = num & mask
  if desired > 0:
    return "on"
  else:
    return "off"
  
print check_bit4(12) # ==> "off"
print check_bit4(14) # ==> "on"
print check_bit4(20) # ==> "on"

and here is my error:

Traceback (most recent call last):
  File "python", line 12, in <module>
  File "python", line 4, in check_bit4
TypeError: 'str' object cannot be interpreted as an index

What am I doing wrong and how do I fix this?


#2

Try with the parameter set to num and remove the second line.

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

>>> print check_bit4(12)
on
>>> 

#3

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