Bitwise Masks


#1



https://www.codecademy.com/courses/python-intermediate-en-KE1UJ/2/1?curriculum_id=4f89dab3d788890003000096#


Code is not returning on when bit 0b1000 is on.


I'm not sure why it's not returning on


def check_bit4(input):
    mask = 0b1000
    desired = input | mask
    if desired > 0b111:
        return "on"
    else:
        return "off"

I figured that I would check between a number with the bit on, and a number for the input. If either number has bit 0b1000 on, then shouldn't it be greater then 0b111?


#2

This is a good code, but why do you use or?

1 | 1 = 1
0 | 1 = 1

It will always return 1. No matter if bit is on or off.

You should use and (&).


#3

I guess I'm still grasping bitwise a little bit. and I meant to type "if desired > 0b1000". I see why I should use & now, thanks. So would you be able to give any examples of where bitwise operators are actually useful other than switching and comparing binary code? <> especially don't make much sense as to why they would be used in functional code.


#4

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