A bitwise operation is a fundamental operation in computer programming that manipulates individual bits within a binary numeral or bit string. These operations are performed directly on the binary representations of numbers, rather than on their decimal or hexadecimal equivalents. Bitwise operations are essential for low-level programming tasks, such as system programming, cryptography, and performance optimization, due to their efficiency and speed.
Types of Bitwise Operations
-
Bitwise AND (&
):
- This operation compares each bit of two operands. If both bits are 1, the resulting bit is set to 1; otherwise, it is set to 0.
- Example: $$ 12 & 25 $$ in binary is $$ 00001100 & 00011001 = 00001000 $$ (decimal 8)[3][5].
-
Bitwise OR (|
):
- This operation compares each bit of two operands. If at least one of the bits is 1, the resulting bit is set to 1.
- Example: $$ 12 | 25 $$ in binary is $$ 00001100 | 00011001 = 00011101 $$ (decimal 29)[3][5].
-
Bitwise XOR (^
):
- This operation compares each bit of two operands. If the bits are different, the resulting bit is set to 1; otherwise, it is set to 0.
- Example: $$ 12 ^ 25 $$ in binary is $$ 00001100 ^ 00011001 = 00010101 $$ (decimal 21)[3][6].
-
Bitwise NOT (~
):
- This is a unary operation that inverts all the bits of the operand, changing 1s to 0s and 0s to 1s.
- Example: $$ \sim 35 $$ in binary is $$ \sim 00100011 = 11011100 $$ (decimal -36 due to two's complement representation)[3][4].
-
Left Shift (<<
):
- This operation shifts the bits of the first operand to the left by the number of positions specified by the second operand, filling the vacated bits with zeros.
- Example: $$ 12 << 2 $$ in binary is $$ 00001100 << 2 ...