c
  1. c-bitwise-operator

C Bitwise Operators

The bitwise operators in C are as follows:

  • & - AND operator
  • | - OR operator
  • ^ - XOR operator
  • ~ - One's complement operator
  • << - Left shift operator
  • >> - Right shift operator

Example

#include <stdio.h>

int main() {
   unsigned int x = 5;  /*  5 = 0000 0101  */
   unsigned int y = 9;  /*  9 = 0000 1001  */
   int result;

   result = x & y;   /*  Bitwise AND operator  */
   printf("x & y = %d\n", result );

   result = x | y;   /*  Bitwise OR operator  */
   printf("x | y = %d\n", result );

   result = x ^ y;   /*  Bitwise XOR operator  */
   printf("x ^ y = %d\n", result );

   result = ~x;      /*  One's complement operator  */
   printf("~x = %d\n", result );

   result = x << 2;  /*  Left shift operator  */
   printf("x << 2 = %d\n", result );

   result = y >> 2;  /*  Right shift operator  */
   printf("y >> 2 = %d\n", result );

   return 0;
}

Output

The output of the above example will be:

x & y = 1
x | y = 13
x ^ y = 12
~x = -6
x << 2 = 20
y >> 2 = 2

Explanation

Bitwise operators in C allow us to manipulate individual bits within an integer variable. The operators perform operations on the binary representation of the variable.

  • The & operator performs a bitwise AND operation.
  • The | operator performs a bitwise OR operation.
  • The ^ operator performs a bitwise XOR operation.
  • The ~ operator performs a one's complement operation.
  • The << operator performs a left shift operation.
  • The >> operator performs a right shift operation.

Use

Bitwise operators are often used in low-level programming, such as working with device drivers and embedded systems. They can also be used in compression and encryption algorithms, as well as in data storage and retrieval applications.

Important Points

Here are some important points to keep in mind when using bitwise operators in C:

  • Bitwise operators only work on integer types (int, char, short, long, etc.).
  • The ~ operator flips all the bits in an integer.
  • Shifting past the size of an integer will result in undefined behavior.
  • Right shifts on signed integers can result in either logical (0) or arithmetic (sign-preserving) shift, depending on the implementation.

Summary

In summary, bitwise operators in C are used to manipulate individual bits within an integer variable. They allow us to perform operations on the binary representation of the variable. Bitwise operators are often used in low-level programming, such as working with device drivers and embedded systems, as well as in compression and encryption algorithms. Understanding the syntax and use cases for these operators is important for anyone working in these fields.

Published on: