How to bitwise shift a Negative Number ?


A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition. While modern processors usually perform addition and multiplication just as fast as bitwise operations due to their longer instruction pipelines and other architectural design choices, bitwise operations do commonly use less power/performance because of the reduced use of resources.

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

#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

Related posts:

About author

This article was written by admin

Admin has over twenty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles. Working presently as Development Manager in India. A firm Believer in Knowledge grows when it shared.

Comments

No Comments

Leave your comment

Your email address will not be published. Required fields are marked *