Bitwise Operators in C


Introduction

Bitwise operators in C allow you to manipulate individual bits within integer data types. These operators provide powerful tools for tasks like setting, clearing, or toggling specific bits, as well as performing bitwise shifts. In this guide, we'll explore the principles of bitwise operators in C and provide sample code to illustrate their usage.


Bitwise Operators

C provides several bitwise operators that operate on the individual bits of integers. The main bitwise operators include:

  • Bitwise AND (&): Performs a bitwise AND operation on each pair of bits.
  • Bitwise OR (|): Performs a bitwise OR operation on each pair of bits.
  • Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on each pair of bits.
  • Bitwise NOT (~): Performs a bitwise NOT operation, inverting each bit.
  • Left Shift (<<): Shifts the bits to the left by a specified number of positions.
  • Right Shift (>>): Shifts the bits to the right by a specified number of positions, with or without sign extension.

Sample Code

Let's explore some examples of bitwise operators in C:


Bitwise AND Operator

#include <stdio.h>
int main() {
int a = 12; // Binary: 1100
int b = 10; // Binary: 1010
int result = a & b;
printf("a & b = %d (Binary: %04b)\\n", result, result);
return 0;
}

Bitwise OR Operator

#include <stdio.h>
int main() {
int a = 12; // Binary: 1100
int b = 10; // Binary: 1010
int result = a | b;
printf("a | b = %d (Binary: %04b)\\n", result, result);
return 0;
}

Bitwise XOR Operator

#include <stdio.h>
int main() {
int a = 12; // Binary: 1100
int b = 10; // Binary: 1010
int result = a ^ b;
printf("a ^ b = %d (Binary: %04b)\\n", result, result);
return 0;
}

Bitwise NOT Operator

#include <stdio.h>
int main() {
int a = 12; // Binary: 1100
int result = ~a;
printf("~a = %d (Binary: %04b)\\n", result, result);
return 0;
}

Left Shift Operator

#include <stdio.h>
int main() {
int a = 12; // Binary: 1100
int result = a << 2;
printf("a << 2 = %d (Binary: %08b)\\n", result, result);
return 0;
}

Right Shift Operator

#include <stdio.h>
int main() {
int a = -12; // Binary: 11111111 11111111 11111111 11110100
int result = a >> 2;
printf("a >> 2 = %d (Binary: %08b)\\n", result, result);
return 0;
}

Conclusion

Bitwise operators in C provide the ability to manipulate individual bits within integers, which is often used for tasks like setting or clearing specific flags, optimizing code, or working with hardware registers. This guide has introduced you to the main bitwise operators and provided sample code to illustrate their usage. As you continue your C programming journey, you'll find bitwise operators to be valuable tools for low-level bit manipulation.