Bitwise Operators are used to perform operations at the bit level (0s and 1s). While most operations work with bytes or words, bitwise operators allow you to modify individual bits within a variable. This is extremely useful in low-level programming, device drivers, and data compression.
C provides six bitwise operators. These work only on integer-type data (int, char, short, etc.) and cannot be used with float or double.
| Operator | Meaning | Description |
|---|---|---|
& |
Binary AND | Sets bit to 1 if both bits are 1. |
| |
Binary OR | Sets bit to 1 if at least one bit is 1. |
^ |
Binary XOR | Sets bit to 1 if bits are different. |
~ |
Binary NOT | Inverts all bits (0 to 1, 1 to 0). |
Shift operators move the bits of a variable to the left or right, which is a very fast way to perform multiplication or division by powers of two.
<<): Shifts bits to the left. Vacant spots are filled with 0. (Equivalent to multiplying by 2n).>>): Shifts bits to the right. (Equivalent to dividing by 2n).Masking is a technique used to check, set, or clear specific bits in a number without affecting the other bits.
Using the bitwise AND operator is much faster than using the modulo (%) operator to check if a number is even or odd.
| Efficiency | Executed directly by the CPU ALU in a single clock cycle. |
| Endianness | Bitwise operations are independent of Big/Little Endian byte order. |
a^=b; b^=a; a^=b;. It's a classic interview trick!