Bit-wise operations
Bit-wise operations are fundamental to low-level programming and are used to manipulate individual bits within binary representations of numbers. Here, we will discuss the basic bit-wise operations: AND, OR, NOR, XOR, and NOT.
AND (&
)
The AND operation compares each bit of two numbers and returns a new number whose bits are set to 1 only if both corresponding bits of the operands are 1.
Example:
5 (0101)
& 3 (0011)
---------
1 (0001)
OR (|
)
The OR operation compares each bit of two numbers and returns a new number whose bits are set to 1 if at least one of the corresponding bits of the operands is 1.
Example:
5 (0101)
| 3 (0011)
---------
7 (0111)
NOR
The NOR operation is the combination of OR followed by NOT. It returns a new number whose bits are set to 1 only if both corresponding bits of the operands are 0.
Example:
5 (0101)
| 3 (0011)
---------
7 (0111)
~ 7 (0111)
---------
8 (1000)
XOR (^
)
The XOR operation compares each bit of two numbers and returns a new number whose bits are set to 1 if the corresponding bits of the operands are different.
Example:
5 (0101)
^ 3 (0011)
---------
6 (0110)
NOT (~
)
The NOT operation inverts all the bits of a number, turning 1s into 0s and 0s into 1s.
Example:
~5 (0101)
---------
10 (1010)
Bit-wise operations are powerful tools in programming, especially in fields like cryptography, network programming, and performance optimization.