Bit wise Operation
Bitwise Operations in C
Bitwise operations in C are used to manipulate individual bits of data. These operations work at the binary level, allowing you to perform operations such as setting, clearing, or toggling specific bits in a binary number. There are several bitwise operators available in C:
Bitwise AND (
&
): Performs a bitwise AND operation between two operands. The result is 1 if both corresponding bits are 1, otherwise, it is 0.Bitwise OR (
|
): Performs a bitwise OR operation between two operands. The result is 1 if at least one of the corresponding bits is 1, otherwise, it is 0.Bitwise XOR (
^
): Performs a bitwise XOR (exclusive OR) operation between two operands. The result is 1 if the corresponding bits are different, otherwise, it is 0.Bitwise NOT (
~
): Performs a bitwise NOT operation on a single operand. It flips each bit, turning 0s into 1s and 1s into 0s.Left Shift (
<<
): Shifts the bits of the left operand to the left by a specified number of positions. Zeros are shifted in from the right, and the leftmost bits are discarded.Right Shift (
>>
): Shifts the bits of the left operand to the right by a specified number of positions. For unsigned types, zeros are shifted in from the left. For signed types, the sign bit is shifted in from the left, which preserves the sign of the number.
Example:
Let's consider an example to illustrate the bitwise operations in C. Suppose we have two variables a
and b
with the following binary representations:
a = 10101010
b = 11001100
- Bitwise AND (
&
): a & b
performs a bitwise AND operation betweena
andb
.The result is
10001000
.Bitwise OR (
|
):a | b
performs a bitwise OR operation betweena
andb
.The result is
11101110
.Bitwise XOR (
^
):a ^ b
performs a bitwise XOR operation betweena
andb
.The result is
01100110
.Bitwise NOT (
~
):~a
performs a bitwise NOT operation ona
.The result is
01010101
.Left Shift (
<<
):a << 2
shifts the bits ofa
two positions to the left.The result is
101010000
.Right Shift (
>>
):b >> 3
shifts the bits ofb
three positions to the right.- The result is
00011001
.
These are the basic bitwise operations in C. They are commonly used in low-level programming, such as manipulating hardware registers or working with binary data.