Alex Rivera | Logout

Logical vs bitwise

Asked 2011-12-07T15:56:57.903
23

What the different between logical operators and, or and bitwise analogs &, | in usage? Is there any difference in efficiency in various solutions?

Edit
Report

1 Answer

11

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)
-----------
= 1101 (13)
Meaning it would print 13.

answered 2012-02-27T21:55:48.553

Your Answer