C Bitwise Operators

Summary: in this tutorial, you’ll learn about the C bitwise operators and how to use them effectively in the program.

Introduction to C bitwise operators

C provides six bitwise operators for manipulating bits. The bitwise operator can only be applied to operands such as char, short, int, and long.

The following table shows all the C bitwise operators:

C Bitwise OperatorsDescription
&Bitwise AND
|Bitwise inclusive OR
^Bitwise exclusive OR
<<Bitwise left shift
>>Bitwise right shift
~one’s complement

The bitwise operators are preferred in some contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations.

C bitwise operator example

Here’s a program that illustrates how to use the C bitwise operators:

#include <stdio.h> int main() { int d1 = 4, /* binary 100 */ d2 = 6, /* binary 110 */ d3; printf("d1=%d, d2 = %d\n", d1, d2); d3 = d1 & d2; printf("Bitwise AND d1 & d2 = %d\n", d3); d3 = d1 | d2; printf("Bitwise OR d1 | d2 = %d\n", d3); d3 = d1 ^ d2; printf("Bitwise XOR d1 ^ d2 = %d\n", d3); d3 = ~d1; printf("Ones complement of d1 = %d\n", d3); d3 = d1 << 2; printf("Left shift by 2 bits d1 << 2 = %d\n", d3); d3 = d1 >> 2; printf("Right shift by 2 bits d1 >> 2 = %d\n", d3); return 0; }
Code language: C++ (cpp)

Output:

d1=4, d2 = 6 Bitwise AND d1 & d2 = 4 Bitwise OR d1 | d2 = 6 Bitwise XOR d1 ^ d2 = 2 Ones complement of d1 = -5 Left shift by 2 bits d1 << 2 = 16 Right shift by 2 bits d1 >> 2 = 1
Code language: C++ (cpp)

Was this tutorial helpful ?