Boolean operators vs Bitwise operators

前端 未结 9 1341
孤街浪徒
孤街浪徒 2020-11-22 06:34

I am confused as to when I should use Boolean vs bitwise operators

  • and vs &
  • or vs |
9条回答
  •  耶瑟儿~
    2020-11-22 07:31

    Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:

    0 < 1 & 0 < 2
    

    versus

    0 < 1 and 0 < 2
    

    To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.

提交回复
热议问题