Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

Left and Right Rotate Bits of a Number in C

$
0
0

Here we’ll see how to write C program to left or right rotate bits of a number. For example, an unsigned integer consists of 32-bit. Number 2591458749 is represented as 10011010011101101000010110111101 in binary. The diagram below shows how the bits of that number will look like after rotating 8 bits.

Left and right rotate bits of a number

Logic to Left Rotate Bits

Say we want to left rotate an integer of size 32 bits by n bits.

  1. Create a number, num1 by left shifting n bits. (num1 = num << n)
  2. Create another number, num2, by right shifting (32-n) bits. (num2 = num >> (32-n))
  3. The result is num1 OR (|) num2.

Logic to Rotate Rotate Bits

Logic is very similar if we want to right rotate an integer of size 32 bits by n bits.

  1. Create a number, num1 by right shifting n bits. (num1 = num >> n)
  2. Create another number, num2, by left shifting (32-n) bits. (num2 = num << (32-n))
  3. The result is num1 OR (|) num2.

The Program

#include <stdio.h>

void binary(unsigned int n)
{
	unsigned int mask = 0x80000000;
    while(mask) {
	  printf("%d", (n&mask)?1:0);
	  mask = mask >> 1;
	}
}

unsigned int left_rotate(unsigned int num, int n) {
  return (num << n) | (num >> (32 - n));
}

unsigned int right_rotate(unsigned int num, int n) {
  return (num >> n) | (num << (32 - n));
}

void main()
{
    unsigned int num = 0, result;
	int n = 0;
	
    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("Binary represntation of the input number:\n");
    binary(num);
    
    printf("\nHow many bits to rotate (0-31)?: ");
    scanf("%d", &n);
    
    result = left_rotate(num, n);
    printf("\n\nAfter left rotating %d bits:\n", n);
    binary(result);
    
    result = right_rotate(num, n);
    printf("\n\nAfter right rotating %d bits:\n", n);
    binary(result);
    
    printf("\n");
}

This program takes an integer as input and prints the binary form of that number. Then it takes the input of how many bits to rotate. It rotates the number using left_rotate() and right_rotate() functions.

Here is the output.

Rotate bits output

The post Left and Right Rotate Bits of a Number in C appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>