C Bitwise shift negative number



In this tutorial we will be learning how to bitwise shift negative number using left and right shift. Tutorial explains everything about negative bitwise shifting.

Bitwise shift 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.

Recommended article : Bitwise left shift | Bitwise right shift

Program #1 : Simple Bitwise shift negative number

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

Output :

fffffff0

Explanation

In this example we know that -

  1. Internal representation of -1 is all 1’s 1111 1111 1111 1111 1111 1111 1111 1111 in an 32 bit compiler.
  2. When we bitwise shift negative number by 4 bits to left least significant 4 bits are filled with 0’s
  3. Format specifier %x prints specified integer value as hexadecimal format
  4. After shifting 1111 1111 1111 1111 1111 1111 1111 0000 = FFFFFFF0 will be printed.
After 1st Shift : [1111 1111 1111 1111 1111 1111 1111 1110]
After 2nd Shift : [1111 1111 1111 1111 1111 1111 1111 1100]
After 3rd Shift : [1111 1111 1111 1111 1111 1111 1111 1000]
After 4th Shift : [1111 1111 1111 1111 1111 1111 1111 0000]

Some more examples

Program #1 : Right bitwise shift 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

Program #2 : Right bitwise shift 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