8.3) Bit Manipulation and Bitwise Operators
Table of Contents
Bit Manipulation and Bitwise Operators
Bit manipulation involves manipulating individual bits within a value using bitwise operators. Bitwise operators allow you to perform operations at the bit level, which can be useful for tasks like setting or clearing specific bits, checking bit patterns, and optimizing memory usage.
1. Bitwise AND (&
) Operator
Performs a bitwise AND operation between corresponding bits of two values.
Example: Using Bitwise AND Operator
#include <stdio.h>
int main() {
unsigned int num1 = 12; // Binary: 1100
unsigned int num2 = 10; // Binary: 1010
unsigned int result = num1 & num2;
printf("Result: %u\n", result); // Binary result: 1000 (8 in decimal)
return 0;
}
Output:
Result: 8
In this example, the bitwise AND operator is used to perform a bitwise AND operation on the binary representations of num1
and num2
, resulting in the binary value 1000
, which is 8 in decimal.
2. Bitwise OR (|
) Operator
Performs a bitwise OR operation between corresponding bits of two values.
Example: Using Bitwise OR Operator
#include <stdio.h>
int main() {
unsigned int num1 = 12; // Binary: 1100
unsigned int num2 = 10; // Binary: 1010
unsigned int result = num1 | num2;
printf("Result: %u\n", result); // Binary result: 1110 (14 in decimal)
return 0;
}
Output:
Result: 14
In this example, the bitwise OR operator is used to perform a bitwise OR operation on the binary representations of num1
and num2
, resulting in the binary value 1110
, which is 14 in decimal.
3. Bitwise XOR (^
) Operator
Performs a bitwise XOR (exclusive OR) operation between corresponding bits of two values.
Example: Using Bitwise XOR Operator
#include <stdio.h>
int main() {
unsigned int num1 = 12; // Binary: 1100
unsigned int num2 = 10; // Binary: 1010
unsigned int result = num1 ^ num2;
printf("Result: %u\n", result); // Binary result: 0110 (6 in decimal)
return 0;
}
Output:
Result: 6
In this example, the bitwise XOR operator is used to perform a bitwise XOR operation on the binary representations of num1
and num2
, resulting in the binary value 0110
, which is 6 in decimal.
4. Bitwise NOT (~
) Operator
Performs a bitwise NOT operation, flipping all the bits of a value.
Example: Using Bitwise NOT Operator
#include <stdio.h>
int main() {
unsigned int num = 10; // Binary: 1010
unsigned int result = ~num;
printf("Result: %u\n", result); // Binary result: 0101 (5 in decimal)
return 0;
}
Output:
Result: 4294967285
In this example, the bitwise NOT operator is used to perform a bitwise NOT operation on the binary representation of num
, resulting in the binary value 0101
, which is 5 in decimal. Note that the output value seems larger due to the use of unsigned integers.
Bitwise operators are powerful tools for working with individual bits in data, which can be especially useful for tasks like bit manipulation, optimizing storage, and working with hardware interfaces.