Right Shift Negative Numbers in C++
We are going to learn how to right shift negative numbers in C++. Right shift is denoted by the operator “>>
“.
Right shifting takes two operands (two numbers) and right shifts the bits of the first operand by the amount of the value of the second operand.
Syntax
x>>y
This will shift the variable x by y amount to the right. We take these variables as binary numbers, i.e, the representation of a number in 0s and 1s.
Example
Let us take a number as -25 and we are interested in right shifting this value. -25 in binary is 11100111. Our common understanding would be to shift this binary value to the right and add a 0 as MSB(Most significant bit). But this is the wrong approach. The MSB bit must be fixed at all times. With this approach, 1 at MSB will be fixed for our example.
Thus the right shifted value of -25 will be 11110011 which is -13 when converted back to decimal.
Example Code
#include<iostream> using namespace std; void print_bin(char num) { int i; for(i=7; i>=0; i--) { if(num & 1<<i) cout<<"1"; else cout<<"0"; } } int main() { char num1 = -25; char i; for(i=0; i<8; i++) { print_bin(num1 >> i); cout<<endl; } return 0; }
Output:
Explanation
- Whenever we get a right shift, we have to check whether the number is even or odd.
- If even, divide the number by 2.
- If odd, divide the number by 2 and add 1 to the result.
- A function print_bin() is defined to convert the decimal number into a binary and then check the MSB.
- The function checks and retains the MSB and shifts the other 7 bits.
- In the main() function, num1 is defined as a character to store the binary converted value.
- For loop is run 8 times to show each and every bit is shifted. Thus, we have 8 answers.
- Each time the value is right shifted once.
Leave a Reply