Java program to Rotate bits

Let’s learn a Java program to rotate bits. Firstly, we have to learn about bit rotation in this tutorial.

In the Bit rotation is an operation, shifting of the bits happens. In which, the bits that slips from one end are get inserted in the other end in bit rotation. This is also acknowledged as Circular shift. In left rotation, bits that slips from left end are get inserted in the right end. In right rotation, bits that slips from right end are get inserted in the left end.
In Java, we have the signed left shift operator “<<” that shifts a bit pattern to the left. Also, we have the signed right shift operator “>>” that shifts a bit pattern to the right. We will use these operators in our program to achieve the rotation of bits.

Below is our Java code to rotate bits

package java;

public class BitsRotation
{
 static int total= 32;

 //Method to make left rotation of n by x bits
 static int leftR(int n,int x)
 {
  return (n << x) | (n >> (total-x));
 }

 //Method to make right rotation of n by x bits
 static int rightR(int n,int x)
 {
  return (n >> x) | (n << (total-x));
 }

 public static void main(String[] args)
 {
  int n= 12;
  int x= 2;

  System.out.println("Left rotation of "+n+" by "+x+" is "+LeftR(n,x));

  System.out.println("Right rotation of "+n+" by "+x+" is "+rightR(n,x));
 }
}

Running our program will give the result given below:

Left rotation  of 12 by 2 is 48

Right rotation of 12 by 2 is 3

Explanation of the code

In the above program, we have created two methods to perform the rotation of bits. In leftR(*) method, we are doing bitwise or of  (n<<x) with (n>>(32-x)). Because in (n<<x) last x bits are 0 and we have to put first 3 bits of n at last. Similarly, in rightR(*) method we are doing bitwise or of (n>>x) with (n<<(32-x)).

In main method, to achieve bit rotation we are simply calling this method by giving two parameters: one is a number of which digits we have to rotate (n)  and second is a number by which it has to rotate (x).

Leave a Reply