Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

Bitwise operators in C are used to manipulate individual bits of a variable directly. These operators work at the bit-level and are particularly useful in embedded systems, device drivers, and low-level programming. There are six bitwise operators in C:

1. Bitwise AND (&):

Definition:

Performs a bitwise AND operation between each pair of corresponding bits.

Example:

int a = 12; // Binary: 1100
int b = 25; // Binary: 11001

int result = a & b; // Binary: 1000 (8 in decimal)

Output:

result is 8.

2. Bitwise OR (|):

Definition:

Performs a bitwise OR operation between each pair of corresponding bits.

Example:

int a = 12; // Binary: 1100
int b = 25; // Binary: 11001

int result = a | b; // Binary: 11101 (29 in decimal)

Output:

result is 29..

3. Bitwise XOR (^):

Definition:

Performs a bitwise XOR (exclusive OR) operation between each pair of corresponding bits.

Example:

int a = 12; // Binary: 1100
int b = 25; // Binary: 11001

int result = a ^ b; // Binary: 10101 (21 in decimal)

Output:

result is 21.

 

4. Bitwise NOT (~):

Definition:

Flips each bit of the operand, changing 1s to 0s and 0s to 1s.

Example:

int a = 12; // Binary: 1100

int result = ~a; // Binary: 11110011 (assuming a 32-bit integer)

Output:

result is a two’s complement representation of the bitwise negation of a.

5. Left Shift (<<):

Definition:

Shifts the bits of the left operand to the left by a specified number of positions, filling the vacant positions with zeros.

Example:

int a = 5; // Binary: 101

int result = a << 2; // Binary: 10100 (20 in decimal)

Output:

result is 20.

 

6. Right Shift (<<):

Definition:

Shifts the bits of the left operand to the right by a specified number of positions. The vacant positions are filled based on the sign bit for signed integers and with zeros for unsigned integers.

Example:

int a = -8; // Binary: 11111111111111111111111111111000 (assuming a 32-bit signed integer)

int result = a >> 2; // Binary: 11111111111111111111111111111110 (sign bit extended)

Output:

Output: result is -2.

 

These examples illustrate the use of bitwise operators in C. It’s important to note that the behavior of right shift may vary for signed and unsigned integers, and care should be taken to understand the underlying representation of integers in the system.