Bitwise operations are used to perform operations on binary numbers at the bit level, manipulating individual bits in data. These operations are fundamental in low-level programming, dealing with binary digits directly. There are several types of bitwise operations, including bitwise AND, OR, XOR, NOT, and bit shifting.
Let's break down the key bitwise operations:
Bitwise AND (&)
The bitwise AND operation compares each bit of two binary numbers. If both bits are 1, the resulting bit is 1; otherwise, it's 0.
Example:
1010 (binary for 10)
& 1100 (binary for 12)
----
1000 (binary for 8)
Bitwise OR (|)
The bitwise OR operation compares each bit of two binary numbers. If either bit is 1, the resulting bit is 1; otherwise, it's 0.
Example:
1010 (binary for 10)
| 1100 (binary for 12)
----
1110 (binary for 14)
Bitwise XOR (^)
The bitwise XOR operation compares each bit of two binary numbers. If the bits are different, the resulting bit is 1; otherwise, it's 0.
Example:
1010 (binary for 10)
^ 1100 (binary for 12)
----
0110 (binary for 6)
Bitwise NOT (~)
The bitwise NOT operation inverts each bit of a binary number. 1 becomes 0, and 0 becomes 1.
Example:
~ 1010 (binary for 10)
----
0101 (binary for -11 in signed binary representation)
Bit Shifting (<<, >>)
Left Shift (<<): Shifts all bits in a binary number to the left by a specified number of positions, filling the vacant positions with 0s.
Right Shift (>>): Shifts all bits in a binary number to the right by a specified number of positions. If it's an arithmetic right shift, it fills the leftmost positions with the sign bit (for signed numbers).
Example of left shift (<<):
1010 << 2 (binary for 10 left shifted by 2 positions)
----
101000 (binary for 40)
Example of right shift (>>):
1010 >> 2 (binary for 10 right shifted by 2 positions)
----
0010 (binary for 2)
In summary, bitwise operations manipulate data at the bit level, and each type of operation has a specific rule for comparing or altering the bits of binary numbers. These operations are widely used in computer science for tasks such as low-level data processing, network programming, and algorithm optimization.