Shift Operators in C
×


Shift Operators in C

33

  Shift operators in C, namely << (left shift) and >> (right shift), are fundamental tools for bitwise manipulation and efficient arithmetic operations.

They allow shifting the bits of a variable's binary representation to the left or right by a specified number of positions.

Types of Shift Operators

Left Shift Operator (<<): Shifts the bits of a number to the left by a specified number of positions, filling the vacant positions with zeros.

Right Shift Operator (>>): Shifts the bits of a number to the right by a specified number of positions.

The behavior of the right shift operator depends on whether the number is signed or unsigned, resulting in distinct outcomes.

For unsigned numbers, vacant positions are filled with zeros.

For signed numbers, the behavior depends on the compiler:

Arithmetic Right Shift: Vacant positions are filled with the sign bit, preserving the sign of the number.

Logical Right Shift: Vacant positions are filled with zeros.


Syntax:

1 Left Shift Operator Syntax:

result = value << n;

2 Right Shift Operator Syntax:

result = value >> n;

Examples:

1 Left Shift Operator

// Program for left shift operator in C
#include<tdio.h> 

int main() {
    int value = 5;
    int n = 2;
    
    int result = value << n; // Left shift value by n positions
    
    printf("Result of left shift: %d\n", result);
    
    return 0;
}

Output:

Result of left shift: 20

2 Right Shift Operator

 // program for Right shift operator in C
#include<stdio.h> 

int main() {
    int value = 20;
    int n = 3;
    
    int result = value >> n; // Right shift value by n positions
    
    printf("Result of right shift: %d\n", result);
    
    return 0;
}

Output:

Result of right shift: 2

These programs demonstrate the usage of left and right shift operators in C programming, showcasing their syntax and functionality.

Left shift is used to multiply a number by powers of 2, while right shift is used for division by powers of 2 or to extract specific bits from a number.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments