BITWISE OPERATOR
In C, bitwise operators are used to perform operations at the
bit level of operands. They manipulate individual bits within variables.
Bitwise operators are particularly useful for low-level programming, such as
working with binary data, setting/clearing specific bits, or implementing
certain algorithms.
Here are the bitwise operators available in C:
1. Bitwise AND (&): Performs a bitwise AND operation on the
corresponding bits of the operands. The result has a 1 bit only if both bits
are 1.
Example:
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a &
b; // Binary result: 0010 (Decimal: 2)
2. Bitwise OR (|): Performs a bitwise OR operation on the
corresponding bits of the operands. The result has a 1 bit if either of the
bits is 1.
Example:
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a | b; // Binary result: 1110 (Decimal: 14)
3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR)
operation on the corresponding bits of the operands. The result has a 1 bit if
the two bits are different.
Example:
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
int result = a ^
b; // Binary result: 1100 (Decimal: 12)
4. Bitwise NOT (~): Performs a bitwise NOT operation, which
flips the bits of the operand. Each 0 bit becomes 1, and each 1 bit becomes 0.
Example:
int a = 10; // Binary: 1010
int result = ~a; // Binary result: 0101 (Decimal: -11, due to
two's complement representation)
5. Left Shift (<<): Shifts the bits of the left operand to
the left by the number of positions specified by the right operand.
Example:
int a = 5;
// Binary: 0101
int result = a <<
2; // Binary result: 10100 (Decimal:
20)
6. Right Shift (>>): Shifts the bits of the left operand
to the right by the number of positions specified by the right operand. It can
be a logical right shift (fills with 0) or an arithmetic right shift (fills
with the sign bit on signed values).
Example:
int a = 20; // Binary: 10100
int result = a >>
2; // Binary result: 00101 (Decimal: 5)
These bitwise operators allow you to manipulate the individual
bits within integers or other suitable data types. They are useful in scenarios
such as setting or clearing specific bits, checking bit flags, or performing
other bitwise operations.