(A bit of a tangent from crypto 101)
-
Core contepts:
- Bitwise operators work on bits.
- Bits are used to express data in binary form.
- Bits can have a value of either 1 (ie TRUE) or 0 (ie FALSE).
-
Higher-level language constructs like floats and strings can all be represented as a series of bytes
- 1 byte = 8 bits
- ie
1100 1001
- Each bit has two states (TRUE or FALSE) and there are 8 bites per byte
- ie
- 2 ^ 8 = 256
- two possible states for each bit, eight bits combined together
- each byte can contain 256 possible values (between 0-255)
- data structures that can take more than 256 values need to be stored using multiple bytes
- 1 byte = 8 bits
-
Bitwise Operators operate on the binary representation of their inputs
- That’s why sometimes the results of the operations don’t seem to make any sense to a human
- examples below
-
When you apply a bitwise operator on two inputs
- it lines up each of the bits contained in the inputs’ bytes and compares them using the chosen bitwise operator
- the comparison goes down the line, comparing each set of two bits and returning the result
Operators:
AND
— returns TRUE (1) if both bits are the sameOR
— returns TRUE (1) if either bit is TRUE (1)XOR
— returns TRUE (1) if only one of the bits is TRUE (1) or FALSE (0) if they’re the sameNOT
— returns TRUE (1) if its input is FALSE (0) [only takes one input?]
Examples from stackoverflow:
201 AND 15:
201: 1100 1001
AND 15: 0000 1111
------------------
IS 9 0000 1001
10 OR 12:
10 | 12
1010 #decimal 10
1100 #decimal 12
1110 #result = 14
Make sense? See also for more examples.