Bitwise Right Shift
Bitwise Right Shift Operator
Java supports two kinds of the bitwise right shift operators which are basically used to perform shift right operations on numbers.
- Signed Right Shift (>>)
- Unsigned Right Shift (>>>)
Signed Right Shift
The Bitwise Signed Right Shift Operator is used to shift the bits to the right of a given number number. It perform the task in three different subtasks:
- It first convert the number into bits.
- It then shifts the specified bits towards right.
- Finally, it convert the these bits back to the number.
public class Main { public static void main(String[] args) { int x = 12; System.out.println("12 in binary form "+Integer.toBinaryString(x)); int y = 2; int shift = x >> y; System.out.println("12 will become : " + shift+" in integer form"); System.out.println("12 in binary form after performing right shift "+Integer.toBinaryString(shift)); } }
Output :
12 in binary form 1100 12 will become : 3 in integer form 12 in binary form after performing right shift 11
Unsigned Right Shift
The Bitwise Unsigned Right Shift Operator is used to shift the bits to the right of a given number number and adds the equal number of zeros at the beginning, which means zero bits are moved in from the left while extra bits that were pushed off to the right are discarded. Since the sign bit is set to 0, the outcome is always positive.
public class Main { public static void main(String[] args) { int x = -12; System.out.println("-12 in binary form "+Integer.toBinaryString(x)); int y = 2; int shift = x >>> y; System.out.println("-12 will become : " + shift+" in integer form"); System.out.println("-12 in binary form after performing unsingned right shift "+Integer.toBinaryString(shift)); } }
Output :
-12 in binary form 11111111111111111111111111110100 -12 will become : 1073741821 in integer form -12 in binary form after performing unsingned right shift 111111111111111111111111111101
Next, the program declares an integer variable y and initializes it with the value of 2. This value will be used as the number of positions to shift the bits of x to the right.
The program then uses the unsigned right shift operator (>>>) to perform the shift operation. The result of this operation is stored in the variable "shift".
Finally, the program prints the integer value of the shifted number "shift" and its binary representation using the Integer.toBinaryString method.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment