Rotate bits of a number

01 Nov, 2021
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end. In right rotation, the bits that fall off at right end are put back at left end. 
Example: Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and first 3 bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (000...11100101) becomes 00..0011100101000. Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in first ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (000...11100101) by 3 becomes 101000..0011100.  
C++
C
Java
Python3
C#
Javascript
// C++ code to rotate bits// of number#include<iostream> using namespace std;#define INT_BITS 32class gfg{     /*Function to left rotate n by d bits*/public:int leftRotate(int n, unsigned int d){         /* In n<<d, last d bits are 0. To     put first 3 bits of n at    last, do bitwise or of n<<d    with n >>(INT_BITS - d) */    return (n << d)|(n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){    /* In n>>d, first d bits are 0.    To put last 3 bits of at    first, do bitwise or of n>>d    with n <<(INT_BITS - d) */    return (n >> d)|(n << (INT_BITS - d));}}; /* Driver code*/int main(){    gfg g;    int n = 16;    int d = 2;    cout << "Left Rotation of " << n <<            " by " << d << " is ";    cout << g.leftRotate(n, d);    cout << "\nRight Rotation of " << n <<            " by " << d << " is ";    cout << g.rightRotate(n, d);    getchar();} // This code is contributed by SoM15242
#include<stdio.h>#define INT_BITS 32 /*Function to left rotate n by d bits*/int leftRotate(int n, unsigned int d){   /* In n<<d, last d bits are 0. To put first 3 bits of n at     last, do bitwise or of n<<d with n >>(INT_BITS - d) */   return (n << d)|(n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/int rightRotate(int n, unsigned int d){   /* In n>>d, first d bits are 0. To put last 3 bits of at     first, do bitwise or of n>>d with n <<(INT_BITS - d) */   return (n >> d)|(n << (INT_BITS - d));} /* Driver program to test above functions */int main(){  int n = 16;  int d = 2;  printf("Left Rotation of %d by %d is ", n, d);  printf("%d", leftRotate(n, d));  printf("\nRight Rotation of %d by %d is ", n, d);  printf("%d", rightRotate(n, d));  getchar();}
// Java code to rotate bits// of numberclass GFG{static final int INT_BITS = 32; /*Function to left rotate n by d bits*/static int leftRotate(int n, int d) {         /* In n<<d, last d bits are 0.       To put first 3 bits of n at       last, do bitwise or of n<<d with       n >>(INT_BITS - d) */    return (n << d) | (n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/static int rightRotate(int n, int d) {         /* In n>>d, first d bits are 0.       To put last 3 bits of at       first, do bitwise or of n>>d       with n <<(INT_BITS - d) */    return (n >> d) | (n << (INT_BITS - d));} // Driver codepublic static void main(String arg[]){    int n = 16;    int d = 2;    System.out.print("Left Rotation of " + n +                          " by " + d + " is ");    System.out.print(leftRotate(n, d));         System.out.print("\nRight Rotation of " + n +                             " by " + d + " is ");    System.out.print(rightRotate(n, d));}} // This code is contributed by Anant Agarwal.
# Python3 code to# rotate bits of number INT_BITS = 32 # Function to left# rotate n by d bitsdef leftRotate(n, d):     # In n<<d, last d bits are 0.    # To put first 3 bits of n at    # last, do bitwise or of n<<d    # with n >>(INT_BITS - d)    return (n << d)|(n >> (INT_BITS - d)) # Function to right# rotate n by d bitsdef rightRotate(n, d):     # In n>>d, first d bits are 0.    # To put last 3 bits of at    # first, do bitwise or of n>>d    # with n <<(INT_BITS - d)    return (n >> d)|(n << (INT_BITS - d)) & 0xFFFFFFFF # Driver program to# test above functionsn = 16d = 2 print("Left Rotation of",n,"by"      ,d,"is",end=" ")print(leftRotate(n, d)) print("Right Rotation of",n,"by"     ,d,"is",end=" ")print(rightRotate(n, d)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to rotate// bits of a numberusing System; class GFG{    static int INT_BITS = 32;     /* Function to left rotate n by d bits*/    static int leftRotate(int n, int d) {                 /* In n<<d, last d bits are 0.        To put first 3 bits of n at        last, do bitwise or of n<<d with        n >>(INT_BITS - d) */        return (n << d) | (n >> (INT_BITS - d));    }         /*Function to right rotate n by d bits*/    static int rightRotate(int n, int d) {                 /* In n>>d, first d bits are 0.        To put last 3 bits of at        first, do bitwise or of n>>d        with n <<(INT_BITS - d) */        return (n >> d) | (n << (INT_BITS - d));    }         // Driver code    public static void Main()    {        int n = 16;        int d = 2;                 Console.Write("Left Rotation of " + n                      + " by " + d + " is ");        Console.Write(leftRotate(n, d));                 Console.Write("\nRight Rotation of " + n                       + " by " + d + " is ");        Console.Write(rightRotate(n, d));    }} // This code is contributed by Sam007
<script> // JavaScript code to rotate bits// of numberlet INT_BITS = 32;      /*Function to left rotate n by d bits*/ function leftRotate( n,  d){       /* In n<<d, last d bits are 0. To     put first 3 bits of n at    last, do bitwise or of n<<d    with n >>(INT_BITS - d) */    return (n << d)|(n >> (INT_BITS - d));} /*Function to right rotate n by d bits*/function rightRotate( n, d){    /* In n>>d, first d bits are 0.    To put last 3 bits of at    first, do bitwise or of n>>d    with n <<(INT_BITS - d) */    return (n >> d)|(n << (INT_BITS - d));}  /* Driver code*/let n = 16;let d = 2;document.write("Left Rotation of " + n +            " by " + d + " is ");document.write(leftRotate(n, d));document.write("<br>");           document.write("\nRight Rotation of " + n +            " by " + d + " is ");document.write(rightRotate(n, d)); </script>
Output : 
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
Time Complexity: O(1)
Auxiliary Space: O(1)
For 16 bit number:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h> using namespace std; #define SHORT_SIZE 16 // function to rotate the given unsigned short// in the left directionunsigned short leftRotate(unsigned short x, short d){    /**     * By doing x << d, we move the first(right most) d bits     * to the left most d bits, and at the same time we move     * the left most d bits to the right side,     * performing OR operation between the two gives use the     * required result.     * */     return (x << d) | (x >> (SHORT_SIZE - d));} // function to rotate the given unsigned short// in the right directionunsigned short rightRotate(unsigned short x, short d){    /**     * By doing x >> d, we move the first(left most) d bits     * to the right most d bits, and at the same time we move     * the right most d bits to the right side,     * performing OR operation between the two gives use the     * required result.     * */     return (x >> d) | (x << (SHORT_SIZE - d));} /* Driver program to test above functions */int main(){    // Test case    unsigned short n = 28;    short d = 2;     cout << leftRotate(n, d) << endl;    cout << rightRotate(n, d) << endl;     return 0;} // This code is contributed by ganesh227
#include <stdio.h>#define SHORT_SIZE 16 // function to rotate the given unsigned short// in the left directionunsigned short leftRotate(unsigned short x, short d){    /**     * By doing x << d, we move the first(right most) d bits     * to the left most d bits, and at the same time we move     * the left most d bits to the right side,     * performing OR operation between the two gives use the     * required result.     * */     return (x << d) | (x >> (SHORT_SIZE - d));} // function to rotate the given unsigned short// in the right directionunsigned short rightRotate(unsigned short x, short d){    /**     * By doing x >> d, we move the first(left most) d bits     * to the right most d bits, and at the same time we move     * the right most d bits to the right side,     * performing OR operation between the two gives use the     * required result.     * */     return (x >> d) | (x << (SHORT_SIZE - d));} /* Driver program to test above functions */int main(){    // Test case    unsigned short n = 28;    short d = 2;    printf("%d\n", leftRotate(n, d));    printf("%d\n", rightRotate(n, d));     return 0;} // This code is contributed by ganesh227
/*package whatever //do not write package name here */ import java.io.*; class GFG {    public static void main (String[] args) {        int N=28;          int D=2;          rotate(N,D);    }      static void rotate(int N, int D)    {        // your code here        int t=16;        int left= ((N<<D) | N>>(t-D)) & 0xFFFF;        int right=((N>>D) | N<<(t-D)) & 0xFFFF;        System.out.println(left);         System.out.println(right);    }   }
SHORT_SIZE = 16 # function to rotate the given unsigned short# in the left directiondef leftRotate(x, d):     return (x << d) | (x >> (SHORT_SIZE - d))   # function to rotate the given unsigned short# in the right directiondef rightRotate(x, d):     return (x >> d) | (x << (SHORT_SIZE - d)) & 0xDDDDDF # Driver program to test above functions# Test casen = 28d = 2 print("Left Rotation of",n,"by"      ,d,"is",end=" ")print(leftRotate(n, d)) print("Right Rotation of",n,"by"     ,d,"is",end=" ")print(rightRotate(n, d)) # This code is contributed by shivanisinghss2110
/*package whatever //do not write package name here */using System;using System.Collections.Generic;public class GFG {    public static void Main(String[] args) {        int N = 28;          int D = 2;          rotate(N, D);    }     // Driver code   static void rotate(int N, int D)    {        int t = 16;        int left = ((N<<D) | N>>(t-D)) & 0xFFFF;        int right = ((N>>D) | N<<(t-D)) & 0xFFFF;        Console.WriteLine(left);         Console.WriteLine(right);    }   } // This code is contributed by umadevi9616
<script> function rotate(N,D){    // your code here        let t = 16;        let left = ((N<<D) | N>>(t-D)) & 0xFFFF;        let right = ((N>>D) | N<<(t-D)) & 0xFFFF;        document.write(left + "<br>");         document.write(right + "<br>");} let N = 28;let D = 2;rotate(N, D); // This code is contributed by avanitrachhadiya2155</script>
Left Rotation of 28 by 2 is 112
Right Rotation of 28 by 2 is 7
Time Complexity : O(1)
Space Complexity : O(1)
Rotate bits of a number | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRotate bits of a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=S2yXCBu3NdQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find any bug in the above program or other ways to solve the same problem.  
SoumikMondal
rohitsingh07052
Kapil1
avanitrachhadiya2155
ganesh227
umadevi9616
shivanisinghss2110
rishavmahato348
rotation
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bits manipulation (Important tactics)
Bit Fields in C
Divide two integers without using multiplication, division and mod operator
Find the element that appears once
C++ bitset and its application
Set, Clear and Toggle a given bit of a number in C
Count total set bits in all numbers from 1 to n
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Position of rightmost set bit
Write an Efficient C Program to Reverse Bits of a Number