22 Apr 2017

How to bitwise shift a Negative Number ?



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.
?
1
2
3
4
5
#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.
?
1
2
3
4
5
6
[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

?
1
2
3
4
5
6
7
8
9
10
11
12
#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 :

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

No comments:

Post a Comment

commnet here