Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python3 Program to Generate all rotations of a number
Next article icon

Python3 Program to Rotate bits of a number

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. 
In the left rotation, the bits that fall off at the left end are put back at the right end. 
In the right rotation, the bits that fall off at the right end are put back at the left end.
 

INTRODUCTION:

In this Python program, we will learn how to rotate the bits of a given number. Bit rotation, also known as bit shifting, is a technique for rotating the bits of a binary number to the left or right. This can be useful in a variety of contexts, such as in computer science and cryptography.

The program will take an integer input and a rotation distance, and will output the resulting rotated number. The program will use bit shifting and bitwise OR operations to accomplish the rotation.

We will begin by declaring the necessary variables and prompting the user for input. Next, we will use bit shifting and bitwise OR to rotate the bits of the input number according to the specified rotation distance. Finally, we will output the resulting rotated number to the console.

EXAMPLE 1: 

Python
def rotate_bits(num, rot):     return (num << rot) & 0xFFFFFFFF  num = int(input("Enter a number: ")) rot = int(input("Enter the number of positions to rotate: "))  result = rotate_bits(num, rot) print("The result of the rotation is:", result) 


Example: 2


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. 
 

Python3
# Python3 code to  # rotate bits of number  INT_BITS = 32  # Function to left # rotate n by d bits def 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 def 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 functions  n = 16 d = 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 

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)

Please refer complete article on Rotate bits of a number for more details!



Next Article
Python3 Program to Generate all rotations of a number
author
kartik
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Python
  • Python Programs
  • rotation
Practice Tags :
  • Bit Magic
  • python

Similar Reads

  • Python3 Program to Rotate digits of a given number by K
    INTRODUCTION:One important point to consider when working with the algorithm to rotate the digits of a given number by k positions is the time complexity. If we were to implement this algorithm using the approach shown in the previous example, the time complexity would be O(n), where n is the number
    4 min read
  • Python3 Program to Generate all rotations of a number
    Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 31
    2 min read
  • Python program to right rotate n-numbers by 1
    Given a number n. The task is to print n-integers n-times (starting from 1) and right rotate the integers by after each iteration.Examples: Input: 6 Output : 1 2 3 4 5 6 2 3 4 5 6 1 3 4 5 6 1 2 4 5 6 1 2 3 5 6 1 2 3 4 6 1 2 3 4 5 Input : 3 Output : 1 2 3 2 3 1 3 1 2 Method 1: Below is the implementa
    2 min read
  • Python Program to Reverse a Number
    We are given a number and our task is to reverse its digits. For example, if the input is 12345 then the output should be 54321. In this article, we will explore various techniques for reversing a number in Python. Using String SlicingIn this example, the Python code reverses a given number by conve
    3 min read
  • Python program to add two binary numbers
    Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum become
    4 min read
  • Python Program to Subtract Two Binary Numbers
    We are given two binary numbers, num1 and num2 and we have to subtract these two binary numbers and return the result. In this article, we will see how we can subtract two binary numbers in Python. Examples: Input: a = "1110" , b = "0110"Output: "1000"Explanation: We can see that when "1110" is subt
    3 min read
  • Python Program to Multiply Two Binary Numbers
    Given two binary numbers, and the task is to write a Python program to multiply both numbers. Example: firstnumber = 110 secondnumber = 10 Multiplication Result = 1100 We can multiply two binary numbers in two ways using python, and these are: Using bin() functions andWithout using pre-defined funct
    2 min read
  • Python Program for Array Rotation
    Here we are going to see how we can rotate array with Python code. Array Rotation: Python Program for Array Rotation ExamplePartitioning the sub arrays and reversing them Approach: Input arr[] = [1, 2, 3, 4, 5, 6, 7, 8], d = 1, size = 8 1) Reverse the entire list by swapping first and last numbers i
    7 min read
  • Python3 Program To Rotate Linked List Block Wise
    Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples: Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1Output: 3->1->2-
    3 min read
  • Python Program to add two hexadecimal numbers
    Given two hexadecimal numbers, write a Python program to compute their sum. Examples: Input: a = "01B", b = "378" Output: 393 Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3, carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 0 0 + 3 + 0 (carry) = 3, hence a
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences