C Bitwise Shift Negative Number

How to bitwise shift a Negative Number ?

We can Also Shift Negative Number using bitwise operators provided by C (Left Shift and Right Shift). We will learn how to use right shift or left shift operators for Negative Number.

Example :

#include<stdio.h>
void main()
{
printf("%x",-1<<4);
}

Answer :

  • Internal Representation of “-1″ is all 1′s 1111 1111 1111 1111
  • When left shifted four times the least significant 4 bits are filled with 0′s .
  • Format Specifier “%x” Prints specified integer value as “Hexadecimal Value”.
  • After Shifting [ 1111 1111 1111 0000 ] = FFF0 will be Printed.
[1111 1111 1111 1111] << 4
After First  Shift : [1111 1111 1111 1110]
After Second Shift : [1111 1111 1111 1100]
After Third  Shift : [1111 1111 1111 1000]
After Fourth Shift : [1111 1111 1111 0000]

Live Example 1 : Right Shift Operator For Negative Number

#include<stdio.h>
int main()
{
int a = -60;
printf("\nNegative Right Shift by 1 Bit : %d",a >> 1);
printf("\nNegative Right Shift by 2 Bits : %d",a >> 2);
printf("\nNegative Right Shift by 3 Bits : %d",a >> 3);
return(0);
}

Output :

Negative Right Shift by 1 Bit  : -30
Negative Right Shift by 2 Bits : -15
Negative Right Shift by 3 Bits : -8

Live Example 2 : Left Shift Operator For Negative Number

#include<stdio.h>
int main()
{
int a = -60;
printf("\nNegative Left Shift by 1 Bit : %d",a << 1);
printf("\nNegative Left Shift by 2 Bits : %d",a << 2);
printf("\nNegative Left Shift by 3 Bits : %d",a << 3);
return(0);
}

Output :

Negative Left Shift by 1 Bit  : -120
Negative Left Shift by 2 Bits : -240
Negative Left Shift by 3 Bits : -480