Logical vs bitwise

こ雲淡風輕ζ 提交于 2019-11-30 15:25:52

Logical operators operate on logical values, while bitwise operators operate on integer bits. Stop thinking about performance, and use them for they're meant for.

if x and y: # logical operation
   ...
z = z & 0xFF # bitwise operation

Logical operators are used for booleans, since true equals 1 and false equals 0. If you use (binary) numbers other than 1 and 0, then any number that's not zero becomes a one.
Ex: int x = 5; (101 in binary) int y = 0; (0 in binary) In this case, printing x && y would print 0, because 101 was changed to 1, and 0 was kept at zero: this is the same as printing true && false, which returns false (0).

On the other hand, bitwise operators perform an operation on every single bit of the two operands (hence the term "bitwise").
Ex: int x = 5; int y = 8; printing x | y (bitwise OR) would calculate this:
000101 (5)
| 1000 (8)
-----------
= 1011 (11)
Meaning it would print 11.

Logical operators are these:

&& || == !

They allow you operate on logical values for example:

(true || false) // evaluates to true
(!true) // evaluates to false

Bitwise operators are these:

& | ^ ~

They allow you to operate on binary bits, like this:

~011 = 100
0101 & 0011 = 0001
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!